Question

What is the use of Object.defineProperty ...

var myObj = {someNum: 123};
Object.defineProperty(myObj, "anotherNum",
{value: 456, writable: true, enumerable: true, configurable: true});
alert(myObj.someNum + " " + myObj.anotherNum);

... if I can also do ...

var myObj = {someNum: 321};
myObj.anotherNum = 654;
alert(myObj.someNum + " " + myObj.anotherNum);

jsfiddle over here

Was it helpful?

Solution

It should be fairly clear: the .defineProperty() method gives you control over how the property can be accessed. When you simply add a property to an object, it's always writable, enumerable, and configurable.

The .defineProperty() method also lets you set up getter and setter functions.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top