我目前使用Function.apply來調用具有動態數量參數的函數,但我無法訪問原始上下文,也沒有任何願望自己設置上下文。我想要的是能夠調用具有可變數量參數的函數,並保留原始上下文。使用原始上下文調用帶有未知數量參數的Javascript函數
或許有些代碼應該告訴你什麼是我想要做的事:
function MulticastDelegate() {
var handlers = [];
this.event = {
subscribe: function(handler) {
if (typeof(handler) === 'function') {
handlers.push(handler);
}
},
unsubscribe: function(handler) {
if (typeof(handler) === 'function') {
handlers.splice(handlers.indexOf(handler),1);
}
}
}
this.execute = function() {
var args = Array.prototype.slice.call(arguments);
for (var handler in handlers) {
// call this with the original context of the handler
handlers[handler].apply(null, args);
}
}
}
從本質上講,我想的apply
行爲 - 的能力來傳遞參數數組 - 無call
行爲 - 改變函數執行的上下文。
我想你在這裏描述的是什麼呢Backbone.js的在其事件綁定框架:http://documentcloud.github.com /backbone/docs/backbone.html#section-12 – nrabinowitz
@nrabinowitz哈哈! GMTA :) –
我認爲你是正確的讓調用者照顧它執行的上下文,通過使用'var self'方法或類似的東西。然後我可以爲'this'提供一個更合適的對象。 –