如何延长Array.prototype.push()? [英] How to extend Array.prototype.push()?
本文介绍了如何延长Array.prototype.push()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想延长的Array.push方法,以便使用按键将引发回调方法,接着执行正常的阵列功能。
我不太知道如何做到这一点,但这里的一些code我一直在玩不成功。
ARR = [];
arr.push =功能(数据){//回调方法放在这里此=的Array.push(数据);
返回this.length;}arr.push('测试');
解决方案
自推允许多个元素推,我用下面的变量,让真正的push方法都论点的论据。
该解决方案不仅影响ARR变量:
arr.push =功能(){
//你想要的这里...
返回Array.prototype.push.apply(这一点,参数);
}
这个解决方案会影响所有的阵列。我不建议你这样做。
Array.prototype.push =(函数(){
VAR原= Array.prototype.push;
返回功能(){
//你想要的这里。
返回original.apply(这一点,参数);
};
})();
I'm trying to extend the Array.push method so that using push will trigger a callback method, then perform the normal array function.
I'm not quite sure how to do this, but here's some code I've been playing with unsuccessfully.
arr = [];
arr.push = function(data){
//callback method goes here
this = Array.push(data);
return this.length;
}
arr.push('test');
解决方案
Since push allows more than one element to be pushed, I use the arguments variable below to let the real push method have all arguments.
This solution only affects the arr variable:
arr.push = function (){
//Do what you want here...
return Array.prototype.push.apply(this,arguments);
}
This solution affects all arrays. I do not recommend that you do that.
Array.prototype.push=(function(){
var original = Array.prototype.push;
return function() {
//Do what you want here.
return original.apply(this,arguments);
};
})();
这篇关于如何延长Array.prototype.push()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文