Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overwrite function of existing object in javascript

Tags:

javascript

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 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");
}

Any ideas?

like image 535
igorti Avatar asked Feb 08 '11 12:02

igorti


People also ask

Can I override a function in JavaScript?

Introduction. It is true that JavaScript supports overriding, not overloading. When you define multiple functions that have the same name, the last one defined will override all the previously defined ones and every time when you invoke a function, the last defined one will get executed.

Which keyword is used to override the functions already existing in JavaScript?

Given an HTML document and the task is to override the function, either predefined function or user-defined function using JavaScript. Approach: When we run the script then Fun() function called.

How do you define a function in JavaScript?

A JavaScript function is defined with the function keyword, followed by a name, followed by parentheses (). Function names can contain letters, digits, underscores, and dollar signs (same rules as variables).


1 Answers

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
like image 169
David Tang Avatar answered Sep 18 '22 01:09

David Tang