ECMAScript 5 为 JavaScript 添加了大量新的对象方法。
// 添加或更改对象属性Object.defineProperty(object, property, descriptor)// 添加或更改多个对象属性Object.defineProperties(object, descriptors)// 访问属性Object.getOwnPropertyDescriptor(object, property)// 以数组返回所有属性Object.getOwnPropertyNames(object)// 以数组返回所有可枚举的属性Object.keys(object)// 访问原型Object.getPrototypeOf(object)// 阻止向对象添加属性Object.preventExtensions(object)// 如果可将属性添加到对象,则返回 trueObject.isExtensible(object)// 防止更改对象属性(而不是值)Object.seal(object)// 如果对象被密封,则返回 trueObject.isSealed(object)// 防止对对象进行任何更改Object.freeze(object)// 如果对象被冻结,则返回 trueObject.isFrozen(object)
Object.defineProperty(object, property, {value : value})
本例更改了属性值:
var person = { firstName: "Bill", lastName : "Gates", language : "EN" };// 更改属性Object.defineProperty(person, "language", {value : "ZH"});
ES5 允许更改以下属性元数据:
writable : true // 属性值可修改enumerable : true // 属性可枚举configurable : true // 属性可重新配置writable : false // 属性值不可修改enumerable : false // 属性不可枚举configurable : false // 属性不可重新配置
ES5 允许更改 getter 和 setter:
// 定义 getterget: function() { return language }// 定义 setterset: function(value) { language = value }
此例使语言为只读:
Object.defineProperty(person, "language", {writable:false});
此例使语言不可枚举:
Object.defineProperty(person, "language", {enumerable:false});
此例列出对象的所有属性:
var person = { firstName: "Bill", lastName : "Gates" language : "EN" };Object.defineProperty(person, "language", {enumerable:false});Object.getOwnPropertyNames(person); // 返回属性数组
此例只列出对象的所有可枚举属性:
var person = { firstName: "Bill", lastName : "Gates" language : "EN" };Object.defineProperty(person, "language", {enumerable:false});Object.keys(person); // 返回可枚举属性的数组
此例向对象添加新属性:
// 创建对象var person = { firstName: "Bill", lastName : "Gates", language : "EN"};// 添加属性Object.defineProperty(person, "year", {value:"2008"});
Object.defineProperty() 方法也可以用于添加 Getter 和 Setter:
// 创建对象var person = {firstName:"Bill", lastName:"Gates"};// 定义 getterObject.defineProperty(person, "fullName", { get : function () {return this.firstName + " " + this.lastName;}});
// 定义对象var obj = {counter:0};// 定义 settersObject.defineProperty(obj, "reset", { get : function () {this.counter = 0;}});Object.defineProperty(obj, "increment", { get : function () {this.counter++;}});Object.defineProperty(obj, "decrement", { get : function () {this.counter--;}});Object.defineProperty(obj, "add", { set : function (value) {this.counter += value;}});Object.defineProperty(obj, "subtract", { set : function (i) {this.counter -= i;}});// 操作计数器:obj.reset;obj.add = 5;obj.subtract = 1;obj.increment;obj.decrement;