Object.defineProperty

Version >= 五

它允許我們使用屬性描述符在現有物件中定義屬性。

var obj = { };

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

console.log(obj.foo);

控制檯輸出

FOO

可以使用以下選項呼叫 Object.defineProperty

Object.defineProperty(obj, 'nameOfTheProperty', {
  value: valueOfTheProperty, 
  writable: true, // if false, the property is read-only
  configurable : true, // true means the property can be changed later
  enumerable : true // true means property can be enumerated such as in a for..in loop
});

Object.defineProperties 允許你一次定義多個屬性。

var obj = {};
Object.defineProperties(obj, {
  property1: {
    value: true,
    writable: true
  },
  property2: {
    value: 'Hello',
    writable: false
  }      
});