[英]Get an object parameter value inside a jQuery function inside an object's method
我有这个:
function test1()
{
this.count = 0;
this.active = 0;
this.enable = function () {this.active = 1;}
this.disable = function () {this.active = 0;}
this.dodo = function ()
{
$("html").mousemove(function(event) {
// I want to get here the "active" param value;
});
}
this.enable();
this.dodo();
}
instance = new test1();
instance.disable();
假设我要在注释的位置检查test1类的活动参数。 我怎么去那里? 谢谢!
如果要访问更高范围的所有成员变量,只需要this
指针从该范围保存到局部变量中,以便可以在另一个范围内使用它:
function test1() {
this.count = 0;
this.active = 0;
this.enable = function () {this.active = 1;}
this.disable = function () {this.active = 0;}
var self = this;
this.dodo = function () {
$("html").mousemove(function(event) {
// I want to get here the "active" param value;
alert(self.active);
});
}
this.enable();
this.dodo();
}
instance = new test1();
instance.disable();
this.dodo = function ()
{
var active = this.active;
$("html").mousemove(function(event) {
alert(active);
});
}
当您调用函数时,“ this”是指调用该函数的对象,或者与关键字new一起使用时新创建的对象。 例如:
var myObject = {};
myObject.Name = "Luis";
myObject.SayMyName = function() {
alert(this.Name);
};
myObject.SayMyName();
请注意,在JavaScript中,有多种方法可以声明,定义和分配字段和方法给对象,以下是相同的代码,其编写方式与您编写的更加相似:
function MyObject() {
this.Name = "Luis";
this.SayMyName = function() {
alert(this.Name);
};
}
var myObject = new MyObject();
myObject.SayMyName();
还有另一种写同一件事的方式:
var myObject = {
Name: "Luis",
SayMyName: function() {
alert(this.Name);
},
};
myObject.SayMyName();
还有几种不同的方法来调用函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.