在对象方法内的jQuery函数内获取对象参数值

时间:2011-12-30 01:05:28

标签: javascript jquery object


我有这个:

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类的活动参数。我怎么能在那里得到它? 谢谢!

3 个答案:

答案 0 :(得分:2)

如果要访问更高范围的所有成员变量,只需将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();

答案 1 :(得分:1)

this.dodo = function ()
            {
                var active = this.active;

                $("html").mousemove(function(event) {
                    alert(active);             
                });
            }

答案 2 :(得分:1)

调用函数时,“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();

还有几种不同的方法来调用函数。

相关问题