传递一个原型's函数作为参数而不丢失'this'上下文
Passing a prototype's function as parameter without losing the 'this' context
我在JavaScript中通过prototype定义了一个'类'。
第一次func()运行,它工作,但当它第二次调用时,通过setTimeout,它失败了,因为这次它已经丢失了对象上下文,即this不再引用对象,但现在引用window。
我是否有办法在使用原型的同时克服这个问题?还是我需要使用闭包来定义一个"类"?
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 Developer Network:
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/bindif (!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;
};
}
你可以把它封装在一个函数中:
var self = this; // reference the value of "this"
setTimeout( function() {self.func();}, 100 );
使用Function.prototype.bind
,或者将setTimeout
回调封装在自己的闭包中:
func: function() {
var self = this;
self.a();
setTimeout( function() {
self.func();
}, 100);
}
相关文章:
- 将函数的上下文应用于javascript变量
- 函数参数中的数据与指定变量之间的任何性能差异
- 使用Express捕获参数
- 参数变量出现ngTable指令问题
- 如何向onClick事件处理程序传递一个接受参数的函数,并且仍然将该函数绑定到组件's”;这个“;上下文
- 如何使用jQuery上下文参数
- 使用数组-apply()中的参数调用函数,但不使用上下文参数
- 函数参数的 JavaScript 执行上下文
- D3 调度传递参数和调用上下文
- Jquery - ajax 回调的上下文不遵循提供的上下文参数
- AJAX:无法通过上下文参数将对象传递到ajaxSuccess函数中
- 将上下文传递到交互式节点外壳导致“;类型错误:沙箱参数mus已转换为上下文;
- 在没有上下文参数的情况下调用本机绑定函数(function.prototype.bind)
- 传递一个原型's函数作为参数而不丢失'this'上下文
- 使用函数'的上下文与传递参数给函数
- 立即运行JavaScript函数,上下文作为参数
- 通过上下文提供对API的访问与通过参数提供对API的访问有什么区别?
- Javascript:使用函数上下文与作为参数传递的好处是什么?
- "上下文”;Firebase.on的参数不起作用
- Javascript 下划线.js - 我必须使用上下文参数和“this”吗?