防止在作为参数传递的函数中丢失 'this' 变量的上下文
Prevent loss of context for 'this' variable in a function passed as a parameter
问题
如何防止在作为参数传递的函数中丢失 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 is not a function
您可以使用 bind
将 this
的值绑定到作为参数引用的 process()
方法
start: function() {
b.start( this.process.bind(this) );
},
问题
如何防止在作为参数传递的函数中丢失 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 is not a function
您可以使用 bind
将 this
的值绑定到作为参数引用的 process()
方法
start: function() {
b.start( this.process.bind(this) );
},