【问题标题】:Prevent loss of context for 'this' variable in a function passed as a parameter防止在作为参数传递的函数中丢失“this”变量的上下文
【发布时间】:2015-06-30 12:36:52
【问题描述】:

问题

如何防止在作为参数传递的函数中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

【问题讨论】:

    标签: javascript function parameters this typeerror


    【解决方案1】:

    您可以使用bindthis 的值绑定到作为参数引用的process() 方法

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

    FIDDLE

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-01-22
      • 2021-09-02
      • 2020-09-13
      • 1970-01-01
      • 2020-10-21
      • 2011-06-12
      • 2018-08-31
      • 1970-01-01
      相关资源
      最近更新 更多