Skip to content Skip to sidebar Skip to footer

Overwrite Function Of Existing Object In Javascript

Consider following code: mynamespace.myclass = function() { this.myfunction = function() { alert('Original'); } } What I'm trying to do is to overwrite myfunction from outside

Solution 1:

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

Post a Comment for "Overwrite Function Of Existing Object In Javascript"