/*
* Copy the enumerable properties of p to o, and return o.
* If o and p have a property by the same name, o's property is overwritten.
* This function does not handle getters and setters or copy attributes.
*/
function extend(o, p) {
for(prop in p) { // For all props in p.
o[prop] = p[prop]; // Add the property to o.
}
return o;
}
/*
* Return a new object that holds the properties of both o and p.
* If o and p have properties by the same name, the values from o are used.
*/
function union(o,p) { return extend(extend({},o), p); }我认为对于union来说,他的意思是“使用p的值”。
我在Chrome上做了测试。我说错了吗?抱歉的。当我学习时,我倾向于非常谨慎,尤其是这是Javascript的第一本书,6ed是最近出版的。
var o= {x:1} 变量p= {x: 2} 函数扩展(o,p){ 用于(在p中的); } 函数并(o,p){ 返回扩展(extend({},o),p); 变量g=并(o,p) g.x 2
谢谢。
发布于 2011-08-11 01:27:39
是的,它应该读取来自p的属性被保存,o被覆盖。
尽管在编写这段代码时,这样做比较安全:
for(var prop in obj) {
if(obj.hasOwnProperty(prop)) {
// now you know it is actually a property on obj and not inherited from elsewhere
}
}发布于 2011-08-11 01:30:38
Flannigan的书被认为是关于javascript的"最不坏“书,所以要谨慎使用。例如,在extend函数中未声明变量支柱,如下所示:
for(prop in p) { // For all props in p.
o[prop] = p[prop];
}应该真正包括一个hasOwnProperty测试,否则它还会复制继承的可枚举属性:
for (var prop in p) {
if (p.hasOwnProperty(prop)) {
o[prop] = p[prop];
}
}是的,“联合”一词可能会误导那些试图严格地将集合论应用于物体的人。如果o已经具有与p上的名称相同的属性,那么它将被赋予与p上的属性相同的值(有效地覆盖one上的值)。
我认为他试图证明,在p上没有等效项的o的现有属性没有被更改或删除。
https://stackoverflow.com/questions/7019807
复制相似问题