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
  }      
});