开发者

Overwrite function of existing object in javascript

开发者 https://www.devze.com 2023-02-09 01:13 出处:网络
Consider following code: mynamespace.myclass = function() { this.myfunction = function() { alert("Original"); }

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.

While adding new functions through proto开发者_如何转开发type 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");
}

Any ideas?


That's because myfunction is being added in the constructor, which happens after the prototype properties are added (so that the "Original" is in fact overwriting the "Overwritten").

You'll have to mimic this behaviour, by overwriting 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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号