簡體   English   中英

權威指南(6ed)錯誤?

[英]The Definitive Guide (6ed) error?

/*
* 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 是最近的。

變量 o = {x:1}

變量 p = {x: 2}

function 擴展(o,p){

 for(prop in p) o[prop] = p[prop]; return o;

}

function union(o,p){

 return extend(extend({},o),p);

var g = union(o,p)

gx

2

謝謝你。

是的,它應該從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
    }
}

Flannigan 的書被認為是 javascript 上“最不壞”的書,因此請謹慎使用。 例如,在擴展function 中,變量prop未聲明,如下所示:

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上的 one 同名的屬性,那么它將被分配與p上的相同的值(有效地覆蓋o上的值)。

我認為他試圖表明op上沒有等價物的現有屬性不會被更改或刪除。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM