gpt4 book ai didi

javascript - 如何调用对象文字中作为参数接收的方法

转载 作者:行者123 更新时间:2023-12-01 02:22:55 24 4
gpt4 key购买 nike

我运行此代码没有任何错误:

(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:无法读取未定义的属性“call”错误。

如何从字符串参数调用函数?

提前致谢。

最佳答案

您需要使用括号获取属性: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; }

关于javascript - 如何调用对象文字中作为参数接收的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49061038/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com