我正在通过原型(prototype)在 JavaScript 中定义一个“类”。
第一次 func() 运行时,它起作用了,但是当它通过 setTimeout 第二次调用时,它失败了,因为这次它丢失了对象上下文,即 I.E. this 不再引用该对象,但现在引用 window。
有没有办法在我仍然使用原型(prototype)的同时克服这个问题?还是我需要改为使用闭包来定义“类”?
function klass(){}
klass.prototype = {
a: function() {
console.log( "Hi" );
},
func: function(){
this.a();
setTimeout( this.func, 100 );
}
};
var x = new klass();
x.func();
最佳答案
使用Function.prototype.bind
:
setTimeout( this.func.bind(this), 100 );
来自 Mozilla 开发者网络:
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/bind
if (!Function.prototype.bind) {
Function.prototype.bind = function (oThis) {
if (typeof this !== "function") {
// closest thing possible to the ECMAScript 5 internal IsCallable function
throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
}
var aArgs = Array.prototype.slice.call(arguments, 1),
fToBind = this,
fNOP = function () {},
fBound = function () {
return fToBind.apply(this instanceof fNOP
? this
: oThis || window,
aArgs.concat(Array.prototype.slice.call(arguments)));
};
fNOP.prototype = this.prototype;
fBound.prototype = new fNOP();
return fBound;
};
}
关于javascript - 在不丢失 'this' 上下文的情况下将原型(prototype)函数作为参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8610320/