如何扩展 Array.prototype.push()? [英] How can I extend Array.prototype.push()?

查看:42
本文介绍了如何扩展 Array.prototype.push()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试扩展 Array.push 方法,以便使用 push 会触发回调方法,然后执行正常的数组功能.

I'm trying to extend the Array.push method so that using push will trigger a callback method and 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');

推荐答案

由于 push 允许推送多个元素,我使用下面的 arguments 变量让真正的 push 方法有所有参数.

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.

这个解决方案只影响 arr 变量:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆