在函数原型中使用_.extend

dar*_*ong 3 javascript prototype extend underscore.js

这些天我看到了很多这样的事情:

function Dog () {
    this.name = 'Fido';
}

_.extend(Dog.prototype, {
    bark: function() {
        return 'BARK, BARK!'
    },
    soilChothingWithDirtyPaws: function () {
        // Some intricated logic here
        return 'There, I did it!';
    }
});
Run Code Online (Sandbox Code Playgroud)

但结果是否与下面的代码不同?

function Dog () {
    this.name = 'Fido';
}
Dog.prototype = {
    bark: function() {
        return 'BARK, BARK!'
    },
    soilChothingWithDirtyPaws: function () {
        // Some intricated logic here
        return 'There, I did it!';
    }
}
Run Code Online (Sandbox Code Playgroud)

我知道下划线的扩展函数应该做什么,但我真的没有在对象的原型中做到这一点 - 当你可以用普通的老香草JS做到这一点,这意味着,我看不出为什么一个人在这里需要中间.我想知道我是否遗漏了一些非常整洁的东西.

这会带来什么好处吗?

如果有人清楚的话,那将是非常好的.非常感谢!

the*_*eye 6

_.extend 是这样定义的,

_.extend = function(obj) {
    each(slice.call(arguments, 1), function(source) {
        if (source) {
            for (var prop in source) {
                obj[prop] = source[prop];
            }
        }
    });
    return obj;
};
Run Code Online (Sandbox Code Playgroud)

它所做的只是迭代从索引1处的参数到结尾的所有元素的属性,并将其添加到传递给它的第一个参数.

因此,从技术上讲,你所做的将产生同样的效果,但有一个微妙的区别.

当您使用时_.extend,您正在扩充Dog.prototype对象,当您指定它时(如在第二个示例中),您正在用Dog.prototype其他对象替换该对象.

  • 区别不是那么微妙,`Dog.prototype.constructor`会有不同的价值! (2认同)