Descriptors and Named Properties

suggest change

Properties are members of an object. Each named property is a pair of (name, descriptor). The name is a string that allows access (using the dot notation object.propertyName or the square brackets notation object['propertyName']). The descriptor is a record of fields defining the bevahiour of the property when it is accessed (what happens to the property and what is the value returned from accessing it). By and large, a property associates a name to a behaviour (we can think of the behaviour as a black box).

There are two types of named properties:

  1. data property: the property’s name is associated with a value.
  2. accessor property: the property’s name is associated with one or two accessor functions.

Demonstration:

obj.propertyName1 = 5; //translates behind the scenes into
                       //either assigning 5 to the value field* if it is a data property
                //or calling the set function with the parameter 5 if accessor property

// *actually whether an assignment would take place in the case of a data property
// also depends on the presence and value of the writable field - on that later on

The property’s type is determined by its descriptor’s fields, and a property cannot be of both types.

Data descriptors -

Sample:

{
   value: 10,
   writable: true;
}

Accessor descriptors -

Sample:

{
    get: function () {
        return 10;
    },
    enumerable: true
}

meaning of fields and their defaults

configurable,enumerable and writable:

get and set:

value:

Example:

var obj = {propertyName1: 1}; //the pair is actually ('propertyName1', {value:1,
                                                                // writable:true,
                                                                // enumerable:true,
                                                                // configurable:true})
Object.defineProperty(obj, 'propertyName2', {get: function() {
                                                console.log('this will be logged ' + 
                             'every time propertyName2 is accessed to get its value');
                                            },
                                        set: function() {
                                                console.log('and this will be logged ' + 
                            'every time propertyName2\'s value is tried to be set')
                  //will be treated like it has enumerable:false, configurable:false
                                            }});
//propertyName1 is the name of obj's data property 
//and propertyName2 is the name of its accessor property

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents