Javascript 在函数原型中使用扩展
这些天我看到了很多这样的事情:Javascript 在函数原型中使用扩展,javascript,underscore.js,prototype,extend,Javascript,Underscore.js,Prototype,Extend,这些天我看到了很多这样的事情: function Dog () { this.name = 'Fido'; } _.extend(Dog.prototype, { bark: function() { return 'BARK, BARK!' }, soilChothingWithDirtyPaws: function () { // Some intricated logic here return 'There
function Dog () {
this.name = 'Fido';
}
_.extend(Dog.prototype, {
bark: function() {
return 'BARK, BARK!'
},
soilChothingWithDirtyPaws: function () {
// Some intricated logic here
return 'There, I did it!';
}
});
但是结果与下面的代码不同吗
function Dog () {
this.name = 'Fido';
}
Dog.prototype = {
bark: function() {
return 'BARK, BARK!'
},
soilChothingWithDirtyPaws: function () {
// Some intricated logic here
return 'There, I did it!';
}
}
<>我知道下划线的作用是什么,但我并不真正明白在对象的原型中做这件事——当你可以用普通的老香草JS来做这件事时,这意味着我不明白为什么这里需要一个中间人。
我想知道我是否错过了一些真正的好东西
那有什么好处吗
如果有人把事情弄清楚,那就太好了。非常感谢 是这样定义的
_.extend = function(obj) {
each(slice.call(arguments, 1), function(source) {
if (source) {
for (var prop in source) {
obj[prop] = source[prop];
}
}
});
return obj;
};
它所做的就是,迭代从索引1的参数到最后的所有元素的属性,并将其添加到传递给它的第一个参数中
因此,从技术上讲,你所做的将产生相同的效果,但有一个细微的区别
当您使用
.extend
时,您是在扩充Dog.prototype
对象,当您分配给它时(如在第二个示例中),您是在用其他对象替换Dog.prototype对象。可能重复@Bergi它根本不是重复的,因为前面提到的问题不涉及下划线的u.extend()方法。我的问题是使用它而不是简单的原型是否有任何好处,而不是如何使用js原型
等于Dog.prototype.bark=function(){…}代码>。我甚至在我的回答中提到了extend
(这是关于扩展与覆盖原型,而不是下划线扩展)。区别并没有那么微妙,Dog.prototype.constructor
将具有不同的值!