简体   繁体   中英

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); }

I think for union , he meant "values from p are used".

I did the test on Chrome. Am I wrong? Sorry. I tend to be very caution when I am learning, especially this is the #1 book for Javascript, and 6ed is recent.

var o = {x:1}

var p = {x: 2}

function extend(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

Thank you.

yeah it should read the properties from p are kept and o are overwritten.

Though when writing this code it is a little safer to do this:

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's book is considered the " least bad " book on javascript, so use with caution. For example, in the extend function the variable prop is not declared and the following:

for(prop in p) { // For all props in p.
    o[prop] = p[prop]; 
}

should really include a hasOwnProperty test, otherwise it will copy inherited enumerable properties also:

for (var prop in p) {
    if (p.hasOwnProperty(prop)) {
      o[prop] = p[prop]; 
    }
}

And yes, the term "union" is probaby misleading to anyone who tries to apply set theory rigorously to objects. If o already has a property with the same name as one on p , then it will be assigned the same value as the one on p (effectively overwriting the value of the one on o ).

I think he is trying to show that existing properties of o that don't have equivalents on p are not changed or deleted.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM