我运行此代码时没有任何错误:
(function(a, b){
return a.foo = {
call: function(name, args) {
this.myFunction.call(null, args)
},
myFunction: function(args) {
console.log("myFunction has been called!");
console.log(args);
}
}
})(window, document);
foo.call('myFunction', ['arg1', 'arg2']);
但是,如果我使用this.name.call(null, args)
代替this.myFunction.call(null, args)
,请执行以下操作:
(function(a, b){
return a.foo = {
call: function(name, args) {
this.name.call(null, args)
},
myFunction: function(args) {
console.log("myFunction has been called!");
console.log(args);
}
}
})(window, document);
foo.call('myFunction', ['arg1', 'arg2']);
我收到Uncaught TypeError: Cannot read property 'call' of undefined
错误。
如何从字符串参数调用函数?
提前致谢。
答案 0 :(得分:2)
您需要使用括号获取属性:this[name].call(null, args)
这样您就可以访问对象foo
(function(a, b){
return a.foo = {
call: function(name, args) {
this[name].call(null, args)
},
myFunction: function(args) {
console.log("myFunction has been called!");
console.log(args);
}
}
})(window, document);
foo.call('myFunction', ['arg1', 'arg2']);
.as-console-wrapper { max-height: 100% !important; top: 0; }