JavaScript ES5 Object Methods


In 2009, ECMAScript 5 introduced many new methods for objects in JavaScript.

Managing Objects

// Create object with an existing object as prototype
Object.create()

// Adding or changing an object property
Object.defineProperty(object, property, descriptor)

// Adding or changing object properties
Object.defineProperties(object, descriptors)

// Accessing Properties
Object.getOwnPropertyDescriptor(object, property)

// Returns all properties as an array
Object.getOwnPropertyNames(object)

// Accessing the prototype
Object.getPrototypeOf(object)

// Returns enumerable properties as an array
Object.keys(object)

Protecting Objects

// Prevents adding properties to an object
Object.preventExtensions(object)

// Returns true if properties can be added to an object
Object.isExtensible(object)

// Prevents changes of object properties (not values)
Object.seal(object)

// Returns true if object is sealed
Object.isSealed(object)

// Prevents any changes to an object
Object.freeze(object)

// Returns true if object is frozen
Object.isFrozen(object)

Changing a Property Value

Syntax

Object.defineProperty(object, property, {value : value})

This sample is changing a property's value.


Changing Meta Data

ES5 enables modification of the metadata for the following properties:

writable : true      // Property value can be changed
enumerable : true    // Property can be enumerated
configurable : true  // Property can be reconfigured
writable : false     // Property value can not be changed
enumerable : false   // Property can be not enumerated
configurable : false // Property can be not reconfigured

ES5 permits the modification of getters and setters.

// Defining a getter
get: function() { return language }
// Defining a setter
set: function(value) { language = value }

This example sets the language to be read-only.

Object.defineProperty(person, "language", {writable:false});

This instance renders language non-countable.

Object.defineProperty(person, "language", {enumerable:false});

Listing All Properties

This example displays all characteristics of an object:


Listing Enumerable Properties

This sample displays only the countable characteristics of an object:


Adding a Property

This example introduces a fresh feature to an object:


Adding Getters and Setters

You can use the Object.defineProperty() method to add Getters and Setters.


A Counter Example