javascript - 防止在作为参数传递的函数中丢失 'this' 变量的上下文

标签 javascript function parameters this typeerror

问题

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

最佳答案

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

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

FIDDLE

关于javascript - 防止在作为参数传递的函数中丢失 'this' 变量的上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29804589/

相关文章:

javascript - 设置循环以解析 JSON 响应

javascript - 使用 three.js 将 2D 旋转到 3D

javascript - Node.js - 如何在函数之间传递参数

types - 指定元组中的项目数

javascript - Heroku(Cedar) + Node + Express + Jade 子目录中的客户端 javascript 文件在本地与 foreman+curl 一起工作,但在推送到 Heroku 时不能

javascript - 如何设置开关按钮的启用和禁用

c# - C# 中有函数类型吗?

c - 调用函数时一些数据从指针中消失

bash - 什么 while(($#));做 ...;转移; done 在 bash 中是什么意思,为什么有人会使用它?

javascript - 在 Javascript 中处理大字符串