JavaScript原型和调用

我将在push方法上添加一个额外的更新功能,代码如下:

function update() {
    console.log("update");
}
let method = 'push';
let oldMethod = Array.prototype[method];
Array.prototype[method] = function () {
    update();
    oldMethod.call(this,...arguments);
}

Can someone explain why I should use oldMethod.call(this,...arguments) rather than oldMethod() only?

评论
  • uharum
    uharum 回复

    If you don't invoke the "real" .push() with .call(), the value of this (the array into which new values are to be pushed) will be unbound and it won't work.