我运行此代码没有任何错误:
(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
错误。
如何从字符串参数调用函数?
提前致谢。
您需要使用括号获取属性:this[name].call(null, args)
这样你就可以访问对象qazxsw poi的属性
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']);