Javascript Object Oriented Design - Javascript Accessor Property Attributes








Accessor properties have two additional attributes.

Because there is no value stored for accessor properties, there is no need for [[Value]] or [[Writable]].

Instead, accessors have [[Get]] and [[Set]], which contain the getter and setter functions, respectively.

We need only define one of these attributes to create the property. If we only define [[Get]] the property is readable, or we can use [[Set]] to set the property to be writable.

If you try to create a property with both data and accessor attributes, you will get an error.

By using accessor property attributes instead of object literal notation we can define those properties on existing objects.

To use object literal notation, we have to define accessor properties when you create the object.

We can specify whether accessor properties are configurable or enumerable.





Example

The following code


var book1 = { 
    _name : "Javascript", 
/*from   w  w w.j a va 2 s .c  om*/
    get name() { 
        console.log("Reading name"); 
        return this._name; 
    }, 

    set name(value) { 
        console.log("Setting name to %s", value); 
        this._name = value; 
    } 
}; 

can be written as follows:


var book1 = { 
    _name : "Javascript" 
}; /*from   w w w  .j  a  va  2  s .  c  o  m*/

Object.defineProperty(book1, "name", { 
    get : function() { 
        console.log("Reading name"); 
        return this._name; 
    }, 
    set : function(value) { 
        console.log("Setting name to %s", value); 
        this._name = value; 
    }, 
    enumerable : true, 
    configurable : true 
}); 




Note

Setting the other attributes ([[Enumerable]] and [[Configurable]]) allows you to change how the accessor property works.

We can create a nonconfigurable, nonenumerable, nonwritable property like this:


var book1 = { 
    _name : "Javascript" 
}; /*w w w .  ja v a 2s. co m*/
Object.defineProperty(book1, "name", { 
    get : function() { 
        console.log("Reading name"); 
        return this._name; 
    } 
}); 

console.log("name" in book1);                      // true 
console.log(book1.propertyIsEnumerable("name"));   // false 
delete book1.name; 
console.log("name" in book1);                      // true 

book1.name = "CSS"; 
console.log(book1.name);                           // "Javascript" 

The code above generates the following result.