我想有一种方法可以为预先存在的功能添加功能,所以我做了这个:
Function.prototype.attachFunction = function(toAttach)
{
var func = this; //This is the original function, which I want to attack toAttach function to.
//Can I do this without wrapping it in a self-executing function? What's the difference?
func = (function()
{
return function()
{
func();
toAttach();
}
})();
return func; //Return the newly made function, not really important.
}
我将它粘贴到 Google Chrome 控制台中,没有错误,但是,它根本没有(或者看起来)改变原始功能。
f = function() {console.log("g");};
f.attachFunction(function(){console.log("New function!");});
f(); //Prints out just "g".