我有一个文件 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/