Skip to content

Instantly share code, notes, and snippets.

@geastwood
Created April 30, 2014 20:54
Show Gist options
  • Save geastwood/11438103 to your computer and use it in GitHub Desktop.
Save geastwood/11438103 to your computer and use it in GitHub Desktop.

Object Descriptor takeaways

A descriptor is an object which describe how the property behaves.

use object literal

Simplest way to define an object is by using object literal, by doing so, the created object are set with implicit descriptors to all "true". As illustrated below:

var objectLiteral = {
    name: 'foo'
};

// to see its descriptor
Object.getOwnPropertyDescriptor(objectLiteral, 'name');

// will log;
{
    value: "foo",
    writable: true,
    enumerable: true,
    configurable: true
}

create constant use descriptor

"writable" property in descriptor controls the whether the properties' value can be changed. This is desired for creating variables behave as constant.

    var foo = {};
    Object.defineProperty(foo, 'name', {
        value: 'foo',
        writable: false // being explicit here, can also omit
    });

    foo.name = 'new foo';
    foo.name; // still log 'foo' instead of 'new foo'

another test

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment