第一部:《You don't know JS: this & Object prototype》
第三章 Object
对象常量
var myObject = {}; Object.defineProperty( myObject, "FAVORITE_NUMBER", { value: 42, writable: false, configurable: false } );
禁止对象扩展
var myObject = { a: 2 }; Object.preventExtensions( myObject ); myObject.b = 3; myObject.b; // undefined
使用preventExtensions方法,可禁止对象再次扩展。
Object.seal(..)
preventExtensions + configurable:false
Object.freeze(..)
s Object.seal(..) + writable:false
对象默认方法[[Get]]、[[PUT]]
自定义Getters和Setters
var myObject = { // define a getter for `a` get a() { return 2; } }; Object.defineProperty( myObject, // target "b", // property name { // descriptor // define a getter for `b` get: function(){ return this.a * 2 }, // make sure `b` shows up as an object property enumerable: true } );
var myObject = { // define a getter for `a` get a() { return this._a_; }, // define a setter for `a` set a(val) { this._a_ = val * 2; } };