2013-05-31 46 views
2

我想知道動態添加屬性到函數原型對象的最佳方式(或者如果它甚至是一個好主意)。動態添加屬性到原型對象

這是我想出了:

['foo', 'bar'].forEach(function(method) { 
    String.prototype[method] = resolve; 
}); 

function resolve() { 
    // Who the hell called me? 
} 

'str'.foo(); 

我調用同一個功能resolve()所有新的屬性,我加入,我需要檢查誰調用的函數(其屬性名)以便根據這些信息來確定實施情況。這都是好奇心的問題,我正在對瘋狂的JavaScript API實現進行一些測試。

你們有什麼建議嗎?

+0

對於那些想知道爲什麼我用類似的東西,你可以看到它在行動上這個庫我提出:https://npmjs.org/package/unicorn –

回答

12
['foo', 'bar'].forEach(function (method) { 
    String.prototype[method] = function() { 
     resolve(method); 
    }; 
}); 

function resolve(method) { 
    alert(method); 
} 

("hello world").foo(); 
("hello world").bar(); 
+0

哇,這是站在我的臉我沒有意識到!謝謝@tracevipin! –