javascript 覆盖javascript中现有对象的功能
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4933288/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Overwrite function of existing object in javascript
提问by igorti
Consider following code:
考虑以下代码:
mynamespace.myclass = function() {
this.myfunction = function() { alert("Original"); }
}
What I'm trying to do is to overwrite myfunction from outside of mynamespace.myclass declaration.
我想要做的是从 mynamespace.myclass 声明之外覆盖 myfunction。
While adding new functions through prototype seems to work ok, if I define a function with the same name the original function doesn't get overwritten:
虽然通过原型添加新函数似乎可以正常工作,但如果我定义一个同名的函数,则原始函数不会被覆盖:
mynamespace.myclass.prototype.myfunction = function() { alert("Overwritten"); }
mynamespace.myclass.prototype.myfunction = function() { alert("Overwritten"); }
Any ideas?
有任何想法吗?
回答by David Tang
That's because myfunctionis being added in the constructor, which happens afterthe prototype properties are added (so that the "Original" is in fact overwriting the "Overwritten").
那是因为myfunction正在添加到构造函数中,这是在添加原型属性之后发生的(因此“原始”实际上覆盖了“覆盖”)。
You'll have to mimic this behaviour, by overwriting mynamespace.myclassitself:
您必须通过覆盖mynamespace.myclass自身来模仿这种行为:
var oldClass = mynamespace.myclass; // Copy original before overwriting
mynamespace.myclass = function () {
// Apply the original constructor on this object
oldClass.apply(this, arguments);
// Now overwrite the target function after construction
this.myfunction = function () { alert("Overwritten"); };
};
mynamespace.prototype = oldClass.prototype; // Same prototype

