Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extending prototype function without overwriting it

I need to fix a bug in the save function of the Parse.Object library. However, when I try to call the original save function in my overwritten prototype, it loops recursively until the stack overflows!

Parse.Object.prototype.save = function (arg1, arg2, arg3) {
    fixIncludedParseObjects(this);

    Parse.Object.prototype.save.call(this, arg1, arg2, arg3); // endless loop
};

How can I change the endless loop line to call the original function made by parse?

Thanks!

like image 538
Garrett Avatar asked Jul 08 '12 07:07

Garrett


People also ask

Can we override prototype in JavaScript?

Prototyping allows objects to inherit, override, and extend functionality provided by other objects in a similar manner as inheritance, overriding, abstraction, and related technologies do in C#, Java, and other languages. Every object you create in JavaScript has a prototype property by default that can be accessed.

What is constructor prototype?

constructor. The constructor property returns a reference to the Object constructor function that created the instance object. Note that the value of this property is a reference to the function itself, not a string containing the function's name.

Are prototypes created for every function?

The answer is Prototype. The prototype is an object that is associated with every functions and objects by default in JavaScript, where function's prototype property is accessible and modifiable and object's prototype property (aka attribute) is not visible. Every function includes prototype object by default.


3 Answers

Similar to accepted answer but maybe a little easier to understand

var originalSaveFn = Parse.Object.prototype.save;
Parse.Object.prototype.save = function(arg1, arg2, arg3) {
    fixIncludedParseObjects(this);
    originalSaveFn.call(this, arg1, arg2, arg3);
};
like image 152
Below the Radar Avatar answered Oct 04 '22 15:10

Below the Radar


Parse.Object.prototype.save = function (save) {
    return function () {
        fixIncludedParseObjects(this);
        //Remember to return and .apply arguments when proxying
        return save.apply(this, arguments);
    };
}(Parse.Object.prototype.save);
like image 23
Esailija Avatar answered Oct 04 '22 15:10

Esailija


Try this:

(function(save) {
  Parse.Object.prototype.save = function (arg1, arg2, arg3) {
    fixIncludedParseObjects(this);
    save.call(this, arg1, arg2, arg3);
  };
}(Parse.Object.prototype.save));
like image 28
xdazz Avatar answered Oct 04 '22 15:10

xdazz