gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 10:41:05 26 4
gpt4 key购买 nike

在下面的例子中,将对象“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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com