扩展原型功能而不覆盖它

时间:2012-07-08 07:27:36

标签: javascript prototype parse-platform

我需要修复Parse.Object库的save函数中的错误。但是,当我尝试在我的覆盖原型中调用原始save函数时,它会递归循环,直到堆栈溢出!

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

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

如何更改无限循环线以调用由解析生成的原始函数?

谢谢!

3 个答案:

答案 0 :(得分:22)

试试这个:

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

答案 1 :(得分:6)

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

答案 2 :(得分:3)

与接受的答案类似,但可能更容易理解

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