2015-11-05 47 views
0

有人问我一个有趣的问题,我不知道该怎么做。我会感谢任何帮助。覆盖的Javascript本地方法,并调用超

问:当你打电话Array.push(),应该推动正常,也应该对自定义函数的调用。

这里是我的尝试:

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

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

但是,这是行不通的。

+0

凡/如何'customMethod'定义?当你的代码现在出现时,它将是未定义的。 –

+1

你重写'push'而不保存原来的一个... – Hacketo

回答

2

它不会工作,因为您引用相同的方法,并导致递归。您必须存储原始的“超级”方法,然后重写它以实现所需的效果。

下面是它如何工作的:

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

你需要让原来实行的备份,并调用,否则你会陷入无限递归。

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

您不应该修改push的原型,因为您打算打破每个外部库。

但是,如果你需要做的,你可以保存旧的推动和重用。

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

而不是这样做,尝试使用外部方法做的东西。

function CustomPush(array, datas) { 
    Array.prototype.push.call(array, datas); 
    if(typeof customMethod === 'function') { 
     customMethod(); 
    } 
}