在通过引用传递的方法中维护它

时间:2012-06-13 19:40:23

标签: javascript jquery

在以下示例中,将参数作为参数发送给方法" lostThis"对象" instObj","这"是窗口对象。

var obj = function() {};
obj.prototype.lostThis = function() {
    console.log('lostThis', this instanceof obj, this);
};

var instObj = new obj;

var caller = {
    runFn: function(fn) {
        fn();
    }
};

caller.runFn(instObj.lostThis);

控制台响应:

lostThis false Window

run example

在下面的例子中(稍微复杂一点),有不同的方法来调用" instObj"在哪里它是相同的和其他我可以保持"这"对象

var obj = function() {};

obj.prototype.methodRefHasThis = function() {
    var t = this;
    return function() {
        console.log('methodRefHasThis ', t instanceof obj, t);
    };
};

obj.prototype.methodRefLostThis = function() {
    console.log('methodRefLostThis ', this instanceof obj, this);
};

obj.prototype.methodRefMaybeThis = function() {
    console.log('methodRefMaybeThis ', this instanceof obj, this);
};

var instObj = new obj;
var caller = {
    runFn: function(fn) {
        fn();
    }
};

// width jQuery
$('button')
    .bind('click', instObj.methodRefHasThis())
    .bind('click', instObj.methodRefLostThis);

caller.runFn(instObj.methodRefHasThis());
caller.runFn(instObj.methodRefLostThis);
caller.runFn(function() {
    instObj.methodRefMaybeThis();
});​

控制台响应:

methodRefHasThis  true obj
methodRefLostThis  false Window
methodRefMaybeThis  true obj

methodRefHasThis  true obj
methodRefLostThis  false <button>​press here​</button>​

run example

据我所知,jQuery将这个方法分配给一个事件,但可以调用方法&#34; methodRefLostThis&#34;没有丢失&#34;这&#34;要通过引用传递的对象?

感谢

@am_not_i_am,@ Dan_avies_Brackett和@Ben_Lee的解决方案

var obj = function() {};
obj.prototype.lostThis = function() {
    console.log('lostThis', this instanceof obj, this);
};

var instObj = new obj;

var caller = {
    runFn: function(fn) {
        fn();
    }
};

caller.runFn(instObj.lostThis.bind(instObj));
caller.runFn($.proxy(instObj.lostThis, instObj));

控制台响应:

lostThis true obj
lostThis true obj

 ​

run example

3 个答案:

答案 0 :(得分:2)

您可以使用bind将对象绑定到被叫方中的this。例如:

caller.runFn(instObj.lostThis.bind(this));

此处,方法运行时的this将转移到this中的lostThis

答案 1 :(得分:2)

有两种方法可以解决这个问题。您可以捕获对this的本地引用(我通常称之为self),然后在方法中使用self.而不是this.,或者您可以使用函数绑定。

Ben Lee给了JS5做绑定的方法;对于不支持Function.bind的浏览器,jQuery.proxy是另一种选择。

答案 2 :(得分:0)

如果您不想使用您发现的某种技术,可以使用Function.prototype.bind将调用上下文绑定到新函数...

caller.runFn(instObj.lostThis.bind(instObj));

这将返回一个新函数,在调用时,将调用上下文设置为您传递给.bind()的第一个参数的任何内容。

传递给.bind()的任何其他参数将被设置为返回函数的固定参数。

相关问题