gpt4 book ai didi

javascript - 当通过调用 method.call(otherObject) 覆盖 this 时,如何获取对 this 的引用?

转载 作者:行者123 更新时间:2023-11-30 13:36:23 25 4
gpt4 key购买 nike

    var A = function(x){
var that = this;
this.a = x;

}

A.prototype = {
init: function(){
alert(this.a); // as that is not found :s
}
};

var a = new A(1);
var b = new A(2)
a.init.call(b);
// I want to alert number 1, how to do it?

我需要它,因为我使用 jQuery 事件。


我恶心的解决方案...不太好

我的问题得到了回答,但是这有一些问题,我必须定义一个局部变量并为每个事件创建一个闭包……恶心!

        var that = this;
this.view.skinAppliedSignal.add(function(){
that.onSkinApplied();
});

//那么在 onSkinApplied 中这是正确的。有什么办法可以不那么笨拙地完成这项工作吗?

最佳答案

一般情况下,您不能那样做。函数运行时唯一存在的 this 是由调用建立的 this

当您建立事件处理程序时,您可以将事物“捕获”在闭包中:

function something() {
$('.whatever').each(function() {
var whatever = $(this);
whatever.find('button').click(function() {
whatever.hide();
});
});
}

在该示例中,“whatever”用于保存来自“each”循环的元素,以便连接到按钮元素的事件处理程序可以访问它。

edit — 根据评论和对问题的更新,很明显可能需要的是类似于“.bind()”函数的东西,它是 ES5 的一部分(由一些库,例如 Prototype、Functional 和 jQuery)。通过使用“绑定(bind)”,您基本上可以将您选择的任何函数包装在另一个 函数中,这样您的函数将始终在 this 设置为某个特定对象的情况下被调用。

关于javascript - 当通过调用 method.call(otherObject) 覆盖 this 时,如何获取对 this 的引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4695814/

25 4 0