[英]Get an object parameter value inside a jQuery function inside an object's method
I have this: 我有这个:
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();
Let's say I want to check the active param of the test1 class in the commented place. 假设我要在注释的位置检查test1类的活动参数。 How can I get it there ? 我怎么去那里? Thanks! 谢谢!
If you want access to all the member variables of the higher scope, you just need to save the this
pointer from that scope into a local variable so you can use it inside the other scope: 如果要访问更高范围的所有成员变量,只需要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);
});
}
When you call a function 'this' refers to the object the function was invoked from, or the newly created object when you use it together with the keyword new. 当您调用函数时,“ this”是指调用该函数的对象,或者与关键字new一起使用时新创建的对象。 For example: 例如:
var myObject = {};
myObject.Name = "Luis";
myObject.SayMyName = function() {
alert(this.Name);
};
myObject.SayMyName();
Note in JavaScript there are multiple ways to declare, define, and assign fields and methods to objects, below is the same code written more similarly to what you wrote: 请注意,在JavaScript中,有多种方法可以声明,定义和分配字段和方法给对象,以下是相同的代码,其编写方式与您编写的更加相似:
function MyObject() {
this.Name = "Luis";
this.SayMyName = function() {
alert(this.Name);
};
}
var myObject = new MyObject();
myObject.SayMyName();
And yet another way to write the same thing: 还有另一种写同一件事的方式:
var myObject = {
Name: "Luis",
SayMyName: function() {
alert(this.Name);
},
};
myObject.SayMyName();
There are also several different ways to invoke a function. 还有几种不同的方法来调用函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.