Daff
Daff

Reputation: 44205

Difference between this property descriptor and property assignment in ECMAScript 5?

I am reading up a little more on ECMAScript 5 (in the browser, using the ES5-shim which I know doesn't support everything). And just to clear up any confusion, considering I have this object (stolen from this post):

var Person = {
    firstName: null, // the person’s first name
    lastName: null // the person’s last name
};

Is there any difference between this:

var Employee = Object.create(Person, {
    id: {
        value: null,
        enumerable: true,
        configurable: true,
        writable: true
    }
});

And this:

var Employee = Object.create(Person);
Employee.id = null;

// Or using jQuery.extend
$.extend(Employee, {
    id : null
});

As far as I understood enumerable, configurable and writable are set to true when defining a property this way (which would also be backwards compatible to legacy JavaScript engines). Am I missing something or can I just omit the verbose property descriptors whenever I want this to be the desired behaviour?

Upvotes: 4

Views: 219

Answers (1)

Šime Vidas
Šime Vidas

Reputation: 185883

They're the same.

When creating new properties by assignment

obj.prop = val;

all three Boolean attributes of the newly created property are set to true.


Also, notice that when adding properties via Object.defineProperty

Object.defineProperty( obj, 'prop', {
    value: val
});

the Boolean attributes are set to false (by default).

Upvotes: 4

Related Questions