learn-javascript-courses / programming-javascript-applications

A question and answer forum for the O'Reilly book, "Programming JavaScript Applications"
6 stars 3 forks source link

Questions re: Chapter 2: Minimize Side Effects #2

Open douglascalhoun opened 9 years ago

douglascalhoun commented 9 years ago

ch02#side-effects

createCart = function (items) {
  var cart = Object.create(cartProto); 
  cart.items = items;
  return cart;
}

"At this point, cart.items is a reference to the prototype items attribute.”

I’m not sure that this is true. I think it is a shared reference to the array ["apple", "pear", "orange"]. cartProto.items should remain an empty array.

I believe that cart.items = items; in createCart masks cartProto.items each time.

Also, it is stated:

cart.items = Object.create(items);

Now the new cart will have its own copy of the item data, so changes will not be de‐ structive to storedCart.

I believe the new cart's items property will be a new empty object with prototypally inherits from the array ["apple", "pear", "orange"] rather than a copy, which could be obtain using cart.items = items.slice();.

ericelliott commented 9 years ago

I believe that cart.items = items; in createCart masks cartProto.items each time.

Correct.

I believe the new cart's items property will be a new empty object with prototypally inherits from the array ["apple", "pear", "orange"] rather than a copy, which could be obtain using cart.items = items.slice();.

Yes, items.slice() would have made a better example. I did this out of habit to share memory by referencing the delegate for unchanged properties, but it's not needed in this context. Using Object.create() to make array "copies" should be considered an anti-pattern. Thank you for your comments.

douglascalhoun commented 9 years ago

image