NoodleFolk
NoodleFolk

Reputation: 2029

Difference between Object.defineProperty and object property literal

What difference ( if any ) is there between the name property of person and person2?

var person = function(){
    var _name;
    var _person = {};

    Object.defineProperties(_person, {
        name: {
            get: function(){ return _name },
            set: function(n) { _name = n; },
            enumerable: true,
            configurable: true
        }
    });

    return _person;
}();
person.name='john';
console.log(person.name);

function Person2()
{
    this.name = undefined;
}
var person2 = new Person2();
person2.name = 'john';
console.log(person2.name);

Upvotes: 2

Views: 2576

Answers (2)

1983
1983

Reputation: 5963

Practical differences? Well:

Object.getOwnPropertyDescriptor(person, 'name') 

will return a value that isn't equivalent to

Object.getOwnPropertyDescriptor(person2, 'name') 

Also these two function calls will have different effects:

Object.defineProperties(person, {name: {set: undefined}});
person.name; // john
Object.defineProperties(person2, {name: {set: undefined}});
person2.name; // undefined

But there aren't any especially significant differences, in my opinion, if you're not messing with property descriptors.

Upvotes: 1

Brennan
Brennan

Reputation: 5732

defineProperties simply gives you more power over the properties you define. If you use dot-notation to define a property as you did with Person2, that property is writeable, deletable, and enumerable by default.

You kept defaults for Person1, one of which is writeable: false, so you can't reassign the attribute unless you use the setter explicitly. In other words, you wouldn't be able to use dot-notation to change that attribute.

Generally there's not really a need for this behavior, so I'd be careful using it as it may cause unexpected results.

Upvotes: 3

Related Questions