簡體   English   中英

防止在作為參數傳遞的函數中丟失'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

當它作為參數引用時,您可以使用bindthis的值bindprocess()方法

start: function() {
    b.start( this.process.bind(this) );
},

小提琴

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM