我正在尝试动态调用对象内部的函数。找到了 apply
函数但没有完全理解它。查看下面的代码,通过触发 Test.checkQueue()
它应该依次调用 showSomething
“方法”。谢谢。
var Test = {
, queue : [{action:'showSomething', id:'1234'},{action:'showOther', id:'456'}]
, showSomething: function(what) {
alert(what);
}
, checkQueue : function() {
console.log('checkQueue');
console.log(this.queue);
if (this.queue.length) {
var do = this.queue.shift();
console.log(do);
// action.action(action.id);
do.action.apply(this, do.id || []);
}
}
};
最佳答案
您在这里使用 apply
有(至少)两个问题。
它是一个函数对象的方法,你好像是在字符串上调用它
它始终将数组作为其第二个参数——您传入的是字符串或空数组。
试着这样调用它:
Test[do.action].apply(this, do.id ? [do.id] : []);
使用 Test[do.action]
将访问实际函数,而不是字符串“showSomething”或“showOther”,以及 do.id ? [do.id] : []
将始终返回一个数组。
关于javascript - 动态函数调用(应用),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1884793/