문제

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