如何扩展Array.prototype.push()?

Geu*_*uis 28 javascript arrays prototype

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

我不太清楚如何做到这一点,但这里有一些我一直在玩的代码都失败了.

arr = [];
arr.push = function(data){

    //callback method goes here

    this = Array.push(data);
    return this.length;

}

arr.push('test');
Run Code Online (Sandbox Code Playgroud)

som*_*ome 71

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

此解决方案仅影响arr变量:

arr.push = function (){
    //Do what you want here...
    return Array.prototype.push.apply(this,arguments);
}
Run Code Online (Sandbox Code Playgroud)

此解决方案影响所有阵列.我不建议你这样做.

Array.prototype.push=(function(){
    var original = Array.prototype.push;
    return function() {
        //Do what you want here.
        return original.apply(this,arguments);
    };
})();
Run Code Online (Sandbox Code Playgroud)

  • @pottedmeat:但它的可读性较差 - 记住,程序不仅是为机器编写的,也是为其他程序员编写的! (9认同)
  • 当分配给'Array.prototype.push`时,你必须非常小心**关于`// Do do you want here`代码的内容.如果它中的任何内容导致调用`Array.push()`(甚至间接),那么你将崩溃堆栈溢出. (7认同)
  • 我只是想强调你的推荐信息,指出忽视它会导致严重的不愉快. (3认同)

cod*_*pig 9

首先你需要子类Array:

ES6 :(与Chrome50 +以外的babel或浏览器不兼容,现在https://kangax.github.io/compat-table/es6/)

class SortedArray extends Array {
    constructor(...args) {
        super(...args);
    }
    push() {
        return super.push(arguments);
    }
}
Run Code Online (Sandbox Code Playgroud)

es5 :( proto几乎已被弃用,但它是目前唯一的解决方案)

function SortedArray() {
    var arr = [];
    arr.push.apply(arr, arguments);
    arr.__proto__ = SortedArray.prototype;
    return arr;
}
SortedArray.prototype = Object.create(Array.prototype);

SortedArray.prototype.push = function() {
    this.arr.push(arguments);
};
Run Code Online (Sandbox Code Playgroud)

  • 好奇为什么有人不会?JS已经改变了. (8认同)

小智 6

Array.prototype.push是在JavaScript 1.2中引入的.它真的很简单:

Array.prototype.push = function() {
    for( var i = 0, l = arguments.length; i < l; i++ ) this[this.length] = arguments[i];
    return this.length;
};
Run Code Online (Sandbox Code Playgroud)

你总是可以在前面添加一些东西.


Pat*_*ick 5

你可以这样做:

arr = []
arr.push = function(data) {
  alert(data); //callback

  return Array.prototype.push.call(this, data);
}
Run Code Online (Sandbox Code Playgroud)

如果你处于没有通话的情况下,你也可以选择这个解决方案:

arr.push = function(data) {
  alert(data); //callback

  //While unlikely, someone may be using psh to store something important
  //So we save it.
  var saved = this.psh;
  this.psh = Array.prototype.push;
  var ret = this.psh(data);
  this.psh = saved;
  return ret;
}
Run Code Online (Sandbox Code Playgroud)

编辑:

虽然我告诉你如何做到这一点,但是使用执行回调的不同方法然后只是调用数组上的推送而不是覆盖推送可能会更好.您最终可能会出现一些意想不到的副作用.例如,push似乎是varadic(采用可变数量的参数,比如printf),并且使用上面的内容会破坏它.

你需要弄乱_Arguments()和_ArgumentsLength()来正确覆盖这个函数.我强烈反对这条路线.

再次编辑:或者您可以使用"参数",这也是有用的.仍然建议不要采取这条路线.