0

当我尝试使用“this”关键字访问对象时,我得到的是“window”对象而不是对象本身,因为我将它的函数绑定到一个事件并且该事件属于 window 对象。

在示例中,alert(this.osd)表示它未定义,因为“window”对象中没有“osd”。那么,解决这个问题的最佳方法是什么?将游戏对象定义为 window.game ?

var game = {

    osd : null,
    stage : null,

    tick : function(){
        alert(this.osd);

    },

    init : function(){

        // Configure the OSD
        this.osd = "a";

        // Preapare the stage;
        this.stage = "b";
        window.addEventListener("click",this.tick);
    }
}

game.init();
4

2 回答 2

3

您需要使用对象上下文调用 tick 方法,如下所示:

var self = this;
window.addEventListener("click", function() {self.tick()});

或者,您可以.bind()在现代浏览器中使用它本质上做同样的事情(它创建一个存根函数,该函数使用正确的对象上下文调用实际方法)。

window.addEventListener("click", this.tick.bind(this));

The issue is that when you pass this.tick to addEventListener(), you are only passing a function reference to the tick function, you aren't actually passing the object reference. So, when addEventListener() calls tick without any object reference, the default value of this for a function call without an object reference is window (when not in strict mode) so that's what you're seeing.

于 2013-03-30T03:16:59.063 回答
-1

You can bind using a closure, like this:

window.addEventListener('click',(function(o){return function(){o.tick()}})(this));

Also, (unrelated to your problem), since you're making an initialiser function, you would be better off using a class/instance setup:

function Game( myParameter ) {
    this.osd = "a";
    this.tick = function( ) {
    }
    window.addEventListener('click',(function(o){return function(){o.tick()}})(this));
}
var game = new Game( 3 );

Notice that game is now created with new, and we can pass parameters to its "constructor" function.

于 2013-03-30T03:17:40.560 回答