我想動態地調用一個對象內部的函數。找到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 || []);
}
}
};
請記住'do'是一個*保留字*。 – CMS 2009-12-10 23:35:46
'queue'前面的逗號是糟糕/草率的語法,它可能會破壞IE。 – 2009-12-10 23:39:12
'做'改變。不要擔心賈斯汀逗號,這是一個節選。我更喜歡逗號的原因之一 - 更容易注意。 – 2009-12-11 15:32:40