扩展原型功能而不覆盖它

Gar*_*ett 10 javascript prototype parse-platform

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

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

    Parse.Object.prototype.save.call(this, arg1, arg2, arg3); // endless loop
};
Run Code Online (Sandbox Code Playgroud)

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

谢谢!

xda*_*azz 22

试试这个:

(function(save) {
  Parse.Object.prototype.save = function (arg1, arg2, arg3) {
    fixIncludedParseObjects(this);
    save.call(this, arg1, arg2, arg3);
  };
}(Parse.Object.prototype.save));
Run Code Online (Sandbox Code Playgroud)

  • 你能解释一下这里发生了什么吗?或者某些链接.谢谢 (4认同)
  • @Adnan你需要将旧的save方法保存到变量中,这样就使用函数参数`save`. (3认同)

Esa*_*ija 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);
Run Code Online (Sandbox Code Playgroud)


Bel*_*dar 6

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

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