考虑以下代码:
mynamespace.myclass = function() {
this.myfunction = function() { alert("Original"); }
}
我想做的是从 mynamespace.myclass 声明之外覆盖 myfunction。
虽然通过原型添加新函数似乎可以正常工作,但如果我定义一个具有相同名称的函数,则原始函数不会被覆盖:
mynamespace.myclass.prototype.myfunction = function() {
alert("Overwritten");
}
有任何想法吗?
那是因为myfunction
被添加到构造函数中,发生这种情况after添加原型属性(以便“原始”实际上覆盖“覆盖”)。
你必须通过覆盖来模仿这种行为mynamespace.myclass
itself:
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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)