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

标签 javascript jquery

在下面的例子中,将对象“instObj”作为参数传递给方法“lostThis”,“this”是窗口对象。

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”的方法,在相同的地方和其他我可以保留“this”对象的方法。

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 将方法分配给事件时,但是我可以调用方法“methodRefLostThis”而不丢失“this”对象以通过引用传递吗?

谢谢

@am_not_i_am、@Dan_Davies_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

最佳答案

您可以使用bind 将对象绑定(bind)到被调用者中的this。例如:

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

这里,方法运行时的this会被转移到lostThis中的this

关于javascript - 在通过引用传递的方法中维护它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11022164/

相关文章:

jquery - Phonegap AJAX 调用失败

javascript - 在 JavaScript 中使用 document.getElementById

javascript - 设置 i18n 的默认值

javascript - Google自定义搜索JS语法错误

javascript - 如何以 Angular 获得图像的扩展?

javascript - 单击按钮后如何将具有多个类的数据属性值输入到 div?

javascript - 获取数据值,如果等于某个值则应用一个类

javascript - 手动触发 jquery Datatable 搜索

javascript - 如何使用 Node 和羽毛笔?

javascript - 如何使用javascript(jquery)计算选中复选框的数量