[英]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
的值bind
到process()
方法
start: function() {
b.start( this.process.bind(this) );
},
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.