【发布时间】:2012-07-13 21:01:15
【问题描述】:
我想有一种方法可以为预先存在的功能添加功能,所以我做了这个:
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".
【问题讨论】:
-
嗯。你确定
this的值吗? -
嗯,原型就是这样工作的,对吧?
-
始终使用
console.log(this)检查。这是个好习惯 -
会的。几分钟后,我正在修复其他东西,现在......
-
一个问题是你只是重新分配
func,它不会覆盖函数的值。请记住,func只是一个指向函数的指针;它不是函数本身。
标签: javascript function prototype