addyosmani / essential-js-design-patterns

Repo for my 'Learning JavaScript Design Patterns' book
http://addyosmani.com/resources/essentialjsdesignpatterns/book/
4.83k stars 792 forks source link

defineProp shorthand #90

Closed neojski closed 11 years ago

neojski commented 11 years ago

Have a look at mdn defineProperty. It looks like defineProp is not really the shorthand for that above code in the book.

Reason: default values for writable, enumerable and configurable is false.

neojski commented 11 years ago

In fact, it's not even working as config was never defined.

addyosmani commented 11 years ago

Confirmed. Looking into this now.

addyosmani commented 11 years ago

Should fix:

// If the above feels a little difficult to read, a short-hand could
// be written as follows:

var defineProp = function ( obj, key, value ){
  var config = {
    value: value,
    writable: true,
    enumerable: true,
    configurable: true
  };
  Object.defineProperty( obj, key, config );
};

// To use, we then create a new empty "person" object
var person = Object.create( null );

// Populate the object with properties
defineProp( person, "car",  "Delorean" );
defineProp( person, "dateOfBirth", "1981" );
defineProp( person, "hasBeard", false );

console.log(person);
// Outputs: Object {car: "Delorean", dateOfBirth: "1981", hasBeard: false}
neojski commented 11 years ago

Yup, this looks much better. I just didn't make a PR with this solution as I didn't know if you just forgot config or I missed something.

neojski commented 11 years ago

This is actually duplicate of #81.

addyosmani commented 11 years ago

Thanks! It was entirely my fault :) I'll apply a patch for this soon. Thanks for noticing the dupe!