[英]Is it legal to extend a "new" instance using underscore _.extend
当然,这样做是合法的:
_.extend({name: 'moe'}, {age: 50});
=> {name: 'moe', age: 50}
如果我 _.extend 两个(或更多)用 new 创建的实例,它是否合法(并且不会导致未来的问题)?
如:
var a = new Block();
var b = new Wood();
_.extend(a,b);
这是_extend
函数(来源):
_.extend = function(obj) {
each(slice.call(arguments, 1), function(source) {
if (source) {
for (var prop in source) {
obj[prop] = source[prop];
}
}
});
return obj;
};
在您的情况下, _.extend(a,b)
将运行
if (b) { // true
for (var prop in b) {
a[prop] = b[prop];
}
}
请注意, for in
循环遍历所有可枚举属性,即使是那些来自原型(不是自己的)的属性。
我不知道这是否是你想要的。
它可能会产生一些问题,例如,如果存在名为 equal 的属性:
Block.prototype.foo = function(){ return this.bar; }
Block.prototype.bar = true;
Wood.prototype.bar = false;
如果要扩展a
与b
, bar
将被覆盖。 然后,如果你调用a.foo
,它会期望a.bar
为true
,但它会是false
。 这可能会导致foo
出现意外错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.