javascript - 当我使用 "self"调用函数时,为什么会丢失对 "module_object[function_name]();"的引用?

标签 javascript node.js function this self

我有一个文件 tools.js,其中有多个函数:

const another_module = require('another_module');

module.exports = {

    js_call: function(args={}) {
        /*  This function is executed when a JavaScript function should be called
            Call structure:
                args = {
                    'object': 'object.name',
                    'function': 'method_name',
                    'params': ['arg1', 'arg2']
                }
        */
        var self = this;
        var o = null;
        if ('object' in args) {
            if (args.object == 'tools') {
                o = self;
            }
            if (args.object == 'another_module') {
                o = another_module;
            }
        }
        if ('function' in args) {
            if ('params' in args) {
                o[args['function']].apply(null, args['params']);
            } else {
                o[args['function']]();
            }
        }
    },

    loaded_function: function (params={}){
        var self = this;
        self.test_function();            // this does not work here >> self.test_function is not a function 
    },

    test_function: function (){
        console.log('TEST');
    }
}

所以如果我在另一个模块中执行此操作:

const tools = require('tools');

params = {
    'object': 'tools',
    'function': 'loaded_function',
}

tools.js_call(params);

我收到错误

self.test_function is not a function

我想知道当我使用 o[args['function']](); 调用函数时是否会丢失 self 上下文o[args['function']].apply(null, args['params']);.

我该如何解决或解决这个问题?

注意:我使用的是 Node.js 8.9.3

最佳答案

如果您使用 apply 并将 self 作为第一个参数,则函数将在与 self 相同的上下文中运行。

o[args['function']].apply(self, args['params']);

关于javascript - 当我使用 "self"调用函数时,为什么会丢失对 "module_object[function_name]();"的引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51900259/

相关文章:

node.js - MongoDB 无法 $unset 特定字段;自动 _id 字段位于末尾

node.js - 如何调用路由模块(node.js)中的内部函数?

javascript - data.addRows 在谷歌图表中不起作用

javascript - 与 Promise 回调混淆的行为

javascript - 使用 jquery 以编程方式添加 onclick 失败

node.js - 使用 NVM 时找不到 NPM 和 NODE 命令

javascript - Angular 指令 - 如何使用 ng-model 设置双向绑定(bind)

MySQL基于条件的多重连接

python - 如果在 python 中成功,将元素添加到集合中会返回 true 吗?

python - 如何在 Python 中定义后缀函数?