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

有帮助吗?

解决方案

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top