javascript原型方法assign VS下划线2;.extend

javascript原型方法assign VS下划线2;.extend,javascript,prototype,underscore.js,extend,Javascript,Prototype,Underscore.js,Extend,以下代码之间有什么区别吗 纯javascript: Array.prototype.addOrRemove = function(value) { var index = _.indexOf(this, value); if (index === -1) { this.push(value); } else { this.splice(index, 1); } return this; }; 下划线扩展: _.exten

以下代码之间有什么区别吗

纯javascript:

Array.prototype.addOrRemove = function(value) {
    var index = _.indexOf(this, value);

    if (index === -1) {
        this.push(value);
    } else {
        this.splice(index, 1);
    }
    return this;
};
下划线扩展:

_.extend(Array.prototype, {
    addOrRemove: function(value) {
        var index = _.indexOf(this, value);

        if (index === -1) {
            this.push(value);
        } else {
            this.splice(index, 1);
        }
        return this;
    }
});

一个比另一个有什么好处吗?

在这种情况下,没有任何好处。如果要添加多个新属性/方法,则下划线方法会工作得更好


但是,我建议不要修改数组原型,除非您知道您正在使用什么库以及它们在做什么,否则如果覆盖某些方法,很容易破坏某些其他库(PrototypeJS)的功能和浏览器本身。不过,这只是一个旁注…

如果您无意中重写了数组方法,下划线方法会让您大吃一惊

var extention = {
    indexOf: function () {
         // ...
    },
addOrRemove: function(value) {
    var index = _.indexOf(this, value);

    if (index === -1) {
        this.push(value);
    } else {
        this.splice(index, 1);
    }
    return this;
    }
}

_.extend(Array.prototype, extention);
如果您忘记了添加的内容或覆盖的本机方法,则查找问题可能会更困难


顺便说一句,Array.prototype方法对性能更友好。

您不需要
Array.prototype=\u.extend(…)
Nope,
\u.extend(obj,…)
直接应用于
obj