JS:这个引用不起作用

时间:2015-05-05 09:12:38

标签: javascript jquery this argument-passing

我想在结构中封装某些对象的Javascript代码,如下所示。但是,我遇到了this的语义问题。

this期间tiles.init()引用tiles对象时,在事件处理程序中它引用了事件,即我无法使用this从我调用其他方法对象

有没有办法将对象传递给事件处理程序,这样我就不必使用全局变量来调用我自己的子例程并仍然保留 this回调上下文?

我张贴了JSFiddle here。这是有效的JS部分:

myData = {
    'color': "red",
    'makeRed': function(){
        // don't want reference to global here!
        $(this).css("color",myData.color);
    },
    'reset': function(){
        $(this).css("color","");
    },
    'init': function(){
        $("#click").hover(this.makeRed,this.reset);
    }
};

myData.init();

我发现了一些像thisthis这样的解决方案来传递其他参数。该问题已标记为this的重复,但使用.bind()会浪费回调中jQuery所需的this

知道如何在不使用全局变量的情况下将事件上下文的tilesthis都添加到处理函数中吗?

1 个答案:

答案 0 :(得分:2)

您可以在init方法

中使用闭包变量
'init': function () {
    var self = this;
    $("#tiles div.tile").hover(function () {
        self.hoverIn(this);
    }, function () {
        self.hoverOut(this);
    });
}

您的构造无效,因为悬停回调中的this未引用tiles对象

相关问题