如何在回调中调用对象的键?

时间:2012-04-04 13:17:30

标签: javascript oop closures

如何在 obj 处理程序函数中获取变量?没有引用 MyClass 中的 obj

    var obj = {
        func: function(){
            var myClass = new MyClass();
            myClass.handler = this.handler;
            myClass.play();        
        },

        handler: function(){
            //Here i don't have access to obj
            console.log(this); //MyClass
            console.log(this.variable); //undefined
        },

        variable:true
    };

    function MyClass(){
        this.play = function(){
            this.handler();
        };

        this.handler = function(){};
    };

    obj.func();

如果您使用Base.js或其他类似的oop方式,那么构建需要您。

_.bindAll(obj)(下划线metod)也不合适。它在Base.js中突破了。

5 个答案:

答案 0 :(得分:2)

使用变量来引用原始上下文:

...
var self = this;
myClass.handler = function(){ self.handler(); };
...

答案 1 :(得分:2)

仅绑定处理程序方法:http://jsfiddle.net/uZN3e/1/

var obj = {
    variable:true,

    func: function(){
        var myClass = new MyClass();
        // notice Function.bind call here
        // you can use _.bind instead to make it compatible with legacy browsers
        myClass.handler = this.handler.bind(this);
        myClass.play();        
    },

    handler: function(){
        console.log(this.variable);
    }
};

function MyClass(){
    this.play = function(){
        this.handler();
    };

    this.handler = function(){};
};

obj.func();
​

答案 2 :(得分:0)

variable之前声明handler

var obj = {
    variable: true, 

    func: function(){
        // ...       
    },

    handler: function(){
        console.log(this.variable); //true
    }
};

答案 3 :(得分:0)

在范围var中声明的obj中使用函数调用来解决它。

var obj = {
    func: function(){
        var self = this;
        var myClass = new MyClass();
        myClass.handler = function() { return this.handler.call(self); };
        myClass.play();        
    },

    handler: function(){
        //Here i don't have access to obj
        console.log(this); //MyClass
        console.log(this.variable); //undefined
    },

    variable:true
};

答案 4 :(得分:0)

您无法访问 obj ,因为绑定到MyClass构造函数的实例 - myClass。如果在处理程序中您希望通过访问 myClass 并访问 obj ,则必须使用 obj 直接命名:

console.log(this); // myClass
console.log(obj.variable); // true

如果你想这个绑定到 obj ,请使用Juan Mellado或gryzzly建议的内容。

相关问题