问题
如何防止在作为参数传递的函数中丢失 this
变量的上下文?
简单示例,也在 JSFiddle 中
var a = {
start: function() {
b.start( this.process );
},
process: function( justAParameter ) {
justAParameter += ' of multiple contexts!'
this.finish( justAParameter );
},
finish: function( finishParameter ) {
console.log( finishParameter );
}
}
var b = {
start: function( justAFunction ) {
justAFunction( 'Hello world' )
}
}
a.start();
预期输出
Hello world of multiple contexts!
收到输出
TypeError: this.finish 不是函数
最佳答案
您可以使用 bind
将 this
的值作为参数引用时绑定(bind)到 process()
方法
start: function() {
b.start( this.process.bind(this) );
},
关于javascript - 防止在作为参数传递的函数中丢失 'this' 变量的上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29804589/