5

如何在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)(下划线方法)也不适合。它是 Base.js 中的中断覆盖。

4

5 回答 5

2

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

...
var self = this;
myClass.handler = function(){ self.handler(); };
...
于 2012-04-04T13:34:40.697 回答
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();
​
于 2012-04-04T13:35:36.603 回答
0

variable之前声明handler

var obj = {
    variable: true, 

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

    handler: function(){
        console.log(this.variable); //true
    }
};
于 2012-04-04T13:22:56.390 回答
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
};
于 2012-04-04T13:38:03.897 回答
0

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

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

如果您想将此绑定到obj ,请使用 Juan Mellado 或 gryzzly 建议的内容。

于 2012-04-04T13:41:13.257 回答