JavaScript Object Properties
In addition to including names and values, attributes contain some of their writable, enumerable, configurable features. There are two types of properties in JavaScript: Data properties and accessor properties.
Data properties:
Configurable: Indicates whether the property can be redefined by deleting the property through the delete, modifying the property's attributes, or changing the property to an accessor property.
Enumerable: Indicates whether the property can be returned through the for-in loop.
Writable: Indicates whether the value of the property can be modified.
Value: The data value that contains this property.
To modify the properties default attribute, use Object.defineproperty ().
var person = {}; Object.defineproperty (person, "name", { configurable:false,//) Once the attribute is defined as not configurable, it can no longer be modified to be configurable. Writable:false, value: "Nicholas" }); Delete Person.name; alert (person.name); Nicholas person.name = "Michael"; alert (person.name); Nicholas
Accessor properties:
Configurable: Indicates whether the property can be redefined by deleting the property through the delete, modifying the property's attributes, or changing the property to an accessor property.
Enumerable: Indicates whether the property can be returned through the for-in loop.
Get: The function that is called when the property is read.
Value: The function that is called when the property is written.
var book = { _year:2004, edition:1 }; Object.defineproperty (book, "Year", { get:function () { return this._year; }, set:function (newvalue { if (NewValue > 2004) { this._year = newvalue; This.edition + = newValue-2004;}} ); Book.year = 2005; alert (book.edition); 2
Note:this example only works in browsers that has implemented the ECMAScript 5
Define multiple properties Object.defineproperties ()
Object.defineproperties (book, { _year: { value:2004 }, edition: { value:1 }, Year : { Get:function () { return this._year; }, set:function (newvalue) { if (NewValue > 2004) { This._year = newvalue; This.edition + = newValue-2004;}}} ); Book.year = 2005; alert (book.edition); 2
Note:this example only works in browsers that has implemented the ECMAScript 5
Properties of the Read attribute
var book = {}; Object.defineproperties (book, {_year: {value:2004}, edition: { Value:1}, Year: {get:function () {return this._year; }, Set:function (NewValue) {if (NewValue > 2004) { This._year = newvalue; This.edition + = newValue-2004; } } } }); var descriptor = object.getownpropertydescriptor (book, "_year"); alert (Descriptor.value); 2004 alert (descriptor.configurable); False alert (typeof Descriptor.get); "Undefined" var descriptor = object.getownpropertydescriptor (book, "Year"); alert (Descriptor.value); Undefined alert (descriptor.enumerable); False alert (typeof Descriptor.get); "Function"
Note:this example only works in browsers that has implemented the ECMAScript 5
JavaScript Object Properties