Overwrite function of existing object in javascript

前端 未结 1 2009
孤城傲影
孤城傲影 2021-02-04 19:19

Consider following code:

mynamespace.myclass = function() {
    this.myfunction = function() { alert("Original"); }
}

What I\'m trying

相关标签:
1条回答
  • 2021-02-04 20:05

    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 讨论(0)
提交回复
热议问题