'use strict'; (function(){ if(!Object.defineProperty){ console.log('瀏覽器不支持defineProperty'); return; } var person = {}; //向person添加name屬性和它的訪問器 Object.defineProperty(person, 'name', { set : function(n){ console.log('set 訪問器'); this.nameValue = n; //一個新的屬性,若是一樣是name的話,就死循環了。 }, get : function(){ console.log('get 訪問器'); return 'my name is ' + this.nameValue; }, //value : 'jeck', //若是在這裏有value或writable特性,就會報錯:Uncaught TypeError: Invalid property. A property cannot both have accessors and be writable or have a value。 enumerable: true, configurable: true }); person.name = "haha"; //觸發set訪問器 console.log(person.name); //觸發get訪問器 output: my name is haha console.log(person.nameValue); //output: haha //向person添加id數據屬性。 Object.defineProperty(person, 'id', { value : '1234567890', writable : false, enumerable : false, configurable : false }); console.log(person.id); //output: 1234567890 //person.id = '0987654321'; //報錯,由於id是隻讀的,不可寫。 //列出對象的屬性 var propertyNames = Object.getOwnPropertyNames(person); for(var i = 0, len = propertyNames.length; i < len; i++){ var name = propertyNames[i] console.log(name + ': ' + person[name]); } /*output: name: my name is haha nameValue: haha id: 1234567890*/ //列出某一屬性的全部特性。 var descriptor = Object.getOwnPropertyDescriptor(person, 'id'); descriptor.writable = true;//這裏將原來的writable特性改成了true。 for(var prop in descriptor){ console.log(prop + ': ' + descriptor[prop]); } /*output: value: 1234567890 writable: true enumerable: false configurable: false*/ //defineProperty的複數版: Object.defineProperties(person, { sex : { value : 'boy', writable : true, enumerable : false, configurable : true }, age : { set : function(x){ this.ageValue = x; }, get : function(){ return this.ageValue; } } }); person.sex = 'girl'; //變性成功! person.age = 23; console.log('sex: ' + person.sex); console.log('age: ' + person.age); /*output: sex: girl age: 23*/ })();