gpt4 book ai didi

javascript - 覆盖Javascript native 方法并调用super

转载 作者:行者123 更新时间:2023-11-28 15:16:46 26 4
gpt4 key购买 nike

有人问了我一个棘手的问题,我不知道该怎么做。我将不胜感激任何帮助。

问题:当您调用Array.push()时,它应该正常推送,并且还应该调用自定义函数。

这是我的尝试:

Array.prototype.push = function() {
Array.prototype.push.call(this, arguments);
if(typeof customMethod === 'function') {
customMethod();
}
}

function customMethod() {
console.log('customMethod called');
}

但这行不通。

最佳答案

它不起作用,因为您引用相同的方法并导致递归。您必须存储原始的“super”方法,然后重写它以达到所需的效果。

它的工作原理如下:

Array.prototype._push = Array.prototype.push;

Array.prototype.push = function() {
this._push.apply(this, arguments);

if(typeof customMethod === 'function') {
customMethod();
}
};

function customMethod() {
console.log('called custom method');
}

var a = [];

a.push(1);
a.push(2);

console.log(a);

关于javascript - 覆盖Javascript native 方法并调用super,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33546811/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com