Object.defineProperty()

  • Revision slug: JavaScript/Reference/Global_Objects/Object/defineProperty
  • Revision title: Object.defineProperty
  • Revision id: 320915
  • Created:
  • Creator: Brettz9
  • Is current revision? No
  • Comment

Revision Content

{{ js_minversion_header("1.8.5") }}

Summary

Defines a new property directly on an object, or modifies an existing property on an object, and returns the object.

Method of Object
Implemented in JavaScript 1.8.5
ECMAScript Edition ECMAScript 5th Edition

Syntax

Object.defineProperty(obj, prop, descriptor)

Parameters

obj
The object on which to define the property.
prop
The name of the property to be defined or modified.
descriptor
The descriptor for the property being defined or modified.

Description

This method allows precise addition to or modification of a property on an object. Normal property addition through assignment creates properties which show up during property enumeration (for...in loop or Object.keys method), whose values may be changed, and which may be deleted. This method allows these extra details to be changed from their defaults.

Property descriptors present in objects come in two main flavors: data descriptors and accessor descriptors. A data descriptor is a property that has a value, which may or may not be writable. An accessor descriptor is a property described by a getter-setter pair of functions. A descriptor must be one of these two flavors; it cannot be both.

Both data and accessor descriptor is an object with the following optional keys:

configurable
true if and only if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object. Defaults to false.
enumerable
true if and only if this property shows up during enumeration of the properties on the corresponding object. Defaults to false.

A data descriptor is an object with the following optional keys:

value
The value associated with the property. Can be any valid JavaScript value (number, object, function, etc) Defaults to undefined.
writable
True if and only if the value associated with the property may be changed with an assignment operator. Defaults to false.

An accessor descriptor is an object with the following optional keys:

get
A function which serves as a getter for the property, or undefined if there is no getter. The function return will be used as the value of property. Defaults to undefined.
set
A function which serves as a setter for the property, or undefined if there is no setter. The function will receive as only argument the new value being assingned to the property. Defaults to undefined.

Creating a property

When the property specified doesn't exist in the object, Object.defineProperty() creates a new property as described. Fields may be omitted from the descriptor, and default values for those fields are imputed. All of the Boolean-valued fields default to false. The value, get, and set fields default to undefined. A property which is defined without get/set/value/writable is called "generic" and is "typed" as a data descriptor.

Examples

var o = {}; // Creates a new object

// Example of an object property added with defineProperty with a data property descriptor
Object.defineProperty(o, "a", {value : 37,
                               writable : true,
                               enumerable : true,
                               configurable : true});
// 'a' property exists in the o object and its value is 37

// Example of an object property added with defineProperty with an accessor property descriptor
var bValue;
Object.defineProperty(o, "b", {get : function(){ return bValue; },
                               set : function(newValue){ bValue = newValue; },
                               enumerable : true,
                               configurable : true});
o.b = 38;
// 'b' property exists in the o object and its value is 38
// The value of o.b is now always identical to bValue, unless o.b is redefined

// You cannot try to mix both :
Object.defineProperty(o, "conflict", { value: 0x9f91102, 
                                       get: function() { return 0xdeadbeef; } });
// throws a TypeError: value appears only in data descriptors, get appears only in accessor descriptors

Modifying a property

When the property already exists, Object.defineProperty() attempts to modify the property according to the values in the descriptor and the object's current configuration. If the old descriptor had its configurable attribute set to false (the property is said to be "non-configurable"), then no attribute besides writable can be changed. In that case, it is also not possible to switch back and forth between the data and accessor property types.

If a property is non-configurable, its writable attribute can only be changed to false.

A TypeError is thrown when attempts are made to change non-configurable property attributes (besides the writable attribute) unless the current and new values are the same.

Writable attribute

When the writable property attribute is set to false, the property is said to be "non-writable". It cannot be reassigned.

Example

var o = {}; // Creates a new object

Object.defineProperty(o, "a", { value : 37,
                                writable : false });

console.log(o.a); // logs 37
o.a = 25; // No error thrown (it would throw in strict mode, even if the value had been the same)
console.log(o.a); // logs 37. The assignment didn't work.

As seen in the example, trying to write into the non-writable property doesn't change it but doesn't throw an error either.

Enumerable attribute

The enumerable property attribute defines whether the property shows up in a for...in loop and Object.keys() or not.

Example

var o = {};
Object.defineProperty(o, "a", { value : 1, enumerable:true });
Object.defineProperty(o, "b", { value : 2, enumerable:false });
Object.defineProperty(o, "c", { value : 3 }); // enumerable defaults to false
o.d = 4; // enumerable defaults to true when creating a property by setting it

for (var i in o) {    
  console.log(i);  
}
// logs 'a' and 'd' (in undefined order)

Object.keys(o); // ["a", "d"]

o.propertyIsEnumerable('a'); // true
o.propertyIsEnumerable('b'); // false
o.propertyIsEnumerable('c'); // false

Configurable attribute

The configurable attribute controls at the same time whether the property can be deleted from the object and whether its attributes (other than writable) can be changed.

Example

var o = {};
Object.defineProperty(o, "a", { get : function(){return 1;}, 
                                configurable : false } );

Object.defineProperty(o, "a", {configurable : true}); // throws a TypeError
Object.defineProperty(o, "a", {enumerable : true}); // throws a TypeError
Object.defineProperty(o, "a", {set : function(){}}); // throws a TypeError (set was undefined previously)
Object.defineProperty(o, "a", {get : function(){return 1;}}); // throws a TypeError (even though the new get does exactly the same thing)
Object.defineProperty(o, "a", {value : 12}); // throws a TypeError

console.log(o.a); // logs 1
delete o.a; // Nothing happens
console.log(o.a); // logs 1

If the configurable attribute of o.a had been true, none of the errors would be thrown and the property would be deleted at the end.

Adding properties and default values

It's important to consider the way default values of attributes are applied. There is often a difference between simply using dot notation to assign a value and using Object.defineProperty(), as shown in the example below.

var o = {};

o.a = 1;
// is equivalent to :
Object.defineProperty(o, "a", {value : 1,
                               writable : true,
                               configurable : true,
                               enumerable : true});


// On the other hand,
Object.defineProperty(o, "a", {value : 1});
// is equivalent to :
Object.defineProperty(o, "a", {value : 1,
                               writable : false,
                               configurable : false,
                               enumerable : false});

Cross-browser concerns

Redefining the length property of an Array object

It is possible to redefine the length property of arrays, but not all browsers permit this redefinition.  Firefox 4 will throw a TypeError on any attempt to redefine the length property of an array.  Versions of Chrome which implement Object.defineProperty() in some circumstances ignore a length value different from the array's current length property, and changing writability seems to silently not work in some circumstances.  Versions of Safari which implement Object.defineProperty() ignore a length value different from the array's current length property, and attempts to change writability execute without error but do not actually change the property's writability.  Only Internet Explorer 9 and later appear to fully and correctly implement redefinition of the length property of arrays.  For now, don't rely on redefining the length property of an array to either work, or to work in a particular manner.

Internet Explorer 8 specific case

Internet Explorer 8 implemented a Object.defineProperty() method that could only be used on DOM objects. A few things need to be noted:

  • Trying to use Object.defineProperty() on native objects throws an error.
  • Property attributes must be set to some values. true, true, true for data descriptor and true for configurable, false for enumerable for accessor descriptor.(?) Any attempt to provide other value(?) will result in an error being thrown.
  • Reconfiguring a property requires first deleting the property. If the property isn't deleted, it stays as it was before the reconfiguration attempt.

Browser compatibility

{{ CompatibilityTable() }}

Feature Firefox (Gecko) Chrome Internet Explorer Opera Safari
Basic support 4 (2) 5 (previous versions untested) 9 (8, but only on DOM objects and with some non-standard behaviors. See above.) 11.60 5.1 (5, but not on DOM objects)
Feature Firefox Mobile (Gecko) Android IE Mobile Opera Mobile Safari Mobile
Basic support {{ CompatGeckoMobile("2") }} {{ CompatVersionUnknown() }} {{ CompatUnknown() }} 11.50 {{ CompatVersionUnknown() }}

Based on Kangax's compat tables.

See also

{{ languages( {"zh-cn": "zh-cn/JavaScript/Reference/Global_Objects/Object/defineProperty" } ) }}

Revision Source

<p>{{ js_minversion_header("1.8.5") }}</p>
<h2 id="summary" name="summary">Summary</h2>
<p>Defines a new property directly on an object, or modifies an existing property on an object, and returns the object.</p>
<table class="standard-table">
  <thead>
    <tr>
      <th class="header" colspan="2">Method of <a href="/en/JavaScript/Reference/Global_Objects/Object" title="en/JavaScript/Reference/Global_Objects/Object"><code>Object</code></a></th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Implemented in</td>
      <td>JavaScript 1.8.5</td>
    </tr>
    <tr>
      <td>ECMAScript Edition</td>
      <td>ECMAScript 5th Edition</td>
    </tr>
  </tbody>
</table>
<h2 id="Syntax" name="Syntax">Syntax</h2>
<p><code>Object.defineProperty(<em>obj</em>, <em>prop</em>, <em>descriptor</em>)</code></p>
<h2 id="Parameters" name="Parameters">Parameters</h2>
<dl>
  <dt>
    <code>obj</code></dt>
  <dd>
    The object on which to define the property.</dd>
  <dt>
    <code>prop</code></dt>
  <dd>
    The name of the property to be defined or modified.</dd>
  <dt>
    <code>descriptor</code></dt>
  <dd>
    The descriptor for the property being defined or modified.</dd>
</dl>
<h2 id="Description">Description</h2>
<p>This method allows precise addition to or modification of a property on an object. Normal property addition through assignment creates properties which show up during property enumeration (<a href="/en/JavaScript/Reference/Statements/for...in" title="en/JavaScript/Reference/Statements/for...in"><code>for...in</code> loop</a> or <a href="/en-US/docs/JavaScript/Reference/Global_Objects/Object/keys" title="/en-US/docs/JavaScript/Reference/Global_Objects/Object/keys">Object.keys method</a>), whose values may be changed, and which may be <a href="/en/JavaScript/Reference/Operators/delete" title="en/JavaScript/Reference/Operators/Special Operators/delete Operator">deleted</a>. This method allows these extra details to be changed from their defaults.</p>
<p>Property descriptors present in objects come in two main flavors: data descriptors and accessor descriptors. A <em><dfn>data descriptor</dfn></em> is a property that has a value, which may or may not be writable. An <dfn>accessor descriptor</dfn> is a property described by a getter-setter pair of functions. A descriptor must be one of these two flavors; it cannot be both.</p>
<p>Both data and accessor descriptor is an object with the following optional keys:</p>
<dl>
  <dt>
    <code>configurable</code></dt>
  <dd>
    <code>true</code> if and only if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object.&nbsp;<strong>Defaults to </strong><strong><code>false</code></strong><strong>.</strong></dd>
  <dt>
    <code>enumerable</code></dt>
  <dd>
    <code>true</code> if and only if this property shows up during enumeration of the properties on the corresponding object.&nbsp;<strong>Defaults to </strong><strong><code>false</code></strong><strong>.</strong></dd>
</dl>
<p>A data descriptor is an object with the following optional keys:</p>
<dl>
  <dt>
    <code>value</code></dt>
  <dd>
    The value associated with the property. Can be any valid JavaScript value (number, object, function, etc) <strong>Defaults to <code>undefined</code>.</strong></dd>
  <dt>
    <code>writable</code></dt>
  <dd>
    True if and only if the value associated with the property may be changed with<code> </code>an <a href="/en-US/docs/JavaScript/Reference/Operators/Assignment_Operators" title="/en-US/docs/JavaScript/Reference/Operators/Assignment_Operators">assignment operator</a>.<strong> Defaults to <code>false</code>.</strong></dd>
</dl>
<p>An accessor descriptor is an object with the following optional keys:</p>
<dl>
  <dt>
    <code>get</code></dt>
  <dd>
    A function which serves as a getter for the property, or <code>undefined</code> if there is no getter. The function return will be used as the value of property.&nbsp;<strong>Defaults to </strong><strong><code>undefined</code></strong><strong>.</strong></dd>
  <dt>
    <code>set</code></dt>
  <dd>
    A function which serves as a setter for the property, or <code>undefined</code> if there is no setter. The function will receive as only argument the new value being assingned to the property. <strong>Defaults to </strong><strong><code>undefined</code></strong><strong>.</strong></dd>
</dl>
<h2 id="Creating_a_property">Creating a property</h2>
<p>When the property specified doesn't exist in the object, <code>Object.defineProperty()</code> creates a new property as described. Fields may be omitted from the descriptor, and default values for those fields are imputed. All of the Boolean-valued fields default to <code>false</code>. The <code>value</code>, <code>get</code>, and <code>set</code> fields default to <code>undefined</code>. A property which is defined without <code>get</code>/<code>set</code>/<code>value</code>/<code>writable</code> is called "generic" and is "typed" as a data descriptor.</p>
<h3 id="Examples">Examples</h3>
<pre class="brush: js">
var o = {}; // Creates a new object

// Example of an object property added with defineProperty with a data property descriptor
Object.defineProperty(o, "a", {value : 37,
                               writable : true,
                               enumerable : true,
                               configurable : true});
// 'a' property exists in the o object and its value is 37

// Example of an object property added with defineProperty with an accessor property descriptor
var bValue;
Object.defineProperty(o, "b", {get : function(){ return bValue; },
                               set : function(newValue){ bValue = newValue; },
                               enumerable : true,
                               configurable : true});
o.b = 38;
// 'b' property exists in the o object and its value is 38
// The value of o.b is now always identical to bValue, unless o.b is redefined

// You cannot try to mix both :
Object.defineProperty(o, "conflict", { value: 0x9f91102, 
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; get: function() { return 0xdeadbeef; } });
// throws a TypeError: value appears only in data descriptors, get appears only in accessor descriptors
</pre>
<h2 id="Modifying_a_property">Modifying a property</h2>
<p>When the property already exists, <code>Object.defineProperty()</code> attempts to modify the property according to the values in the descriptor and the object's current configuration. If the old descriptor had its <code>configurable</code> attribute set to <code>false</code> (the property is said to be "non-configurable"), then no attribute besides <code>writable</code> can be changed. In that case, it is also not possible to switch back and forth between the data and accessor property types.</p>
<p>If a property is non-configurable, its <code>writable</code> attribute can only be changed to <code>false</code>.</p>
<p>A <a href="/en/JavaScript/Reference/Global_Objects/TypeError" title="en/JavaScript/Reference/Global Objects/TypeError"><code>TypeError</code></a> is thrown when attempts are made to change non-configurable property attributes (besides the <code>writable</code> attribute) unless the current and new values are the same.</p>
<h2 id="Writable_attribute">Writable attribute</h2>
<p>When the <code>writable</code> property attribute is set to <code>false</code>, the property is said to be "non-writable". It cannot be reassigned.</p>
<h3 id="Example">Example</h3>
<pre class="brush: js">
var o = {}; // Creates a new object

Object.defineProperty(o, "a", { value : 37,
                                writable : false });

console.log(o.a); // logs 37
o.a = 25; // No error thrown (it would throw in strict mode, even if the value had been the same)
console.log(o.a); // logs 37. The assignment didn't work.
</pre>
<p>As seen in the example, trying to write into the non-writable property doesn't change it but doesn't throw an error either.</p>
<h2 id="Enumerable_attribute">Enumerable attribute</h2>
<p>The <code>enumerable</code> property attribute defines whether the property shows up in a <code><a href="/en/JavaScript/Reference/Statements/for...in" title="en/JavaScript/Reference/Statements/for...in">for...in</a></code> loop and Object.keys() or not.</p>
<h3 id="Example">Example</h3>
<pre class="brush: js">
var o = {};
Object.defineProperty(o, "a", { value : 1, enumerable:true });
Object.defineProperty(o, "b", { value : 2, enumerable:false });
Object.defineProperty(o, "c", { value : 3 }); // enumerable defaults to false
o.d = 4; // enumerable defaults to true when creating a property by setting it

for (var i in o) {    
&nbsp;&nbsp;console.log(i);  
}
// logs 'a' and 'd' (in undefined order)

Object.keys(o); // ["a", "d"]

o.propertyIsEnumerable('a'); // true
o.propertyIsEnumerable('b'); // false
o.propertyIsEnumerable('c'); // false
</pre>
<h2 id="Configurable_attribute">Configurable attribute</h2>
<p>The <code>configurable</code> attribute controls at the same time whether the property can be deleted from the object and whether its attributes (other than <code>writable</code>) can be changed.</p>
<h3 id="Example">Example</h3>
<pre class="brush: js">
var o = {};
Object.defineProperty(o, "a", { get : function(){return 1;}, 
                                configurable : false } );

Object.defineProperty(o, "a", {configurable : true}); // throws a TypeError
Object.defineProperty(o, "a", {enumerable : true}); // throws a TypeError
Object.defineProperty(o, "a", {set : function(){}}); // throws a TypeError (set was undefined previously)
Object.defineProperty(o, "a", {get : function(){return 1;}}); // throws a TypeError (even though the new get does exactly the same thing)
Object.defineProperty(o, "a", {value : 12}); // throws a TypeError

console.log(o.a); // logs 1
delete o.a; // Nothing happens
console.log(o.a); // logs 1
</pre>
<p>If&nbsp;the <code>configurable</code> attribute of <code>o.a</code> had been <code>true</code>, none of the errors would be thrown and the property would be deleted at the end.</p>
<h2 id="Adding_properties_and_default_values">Adding properties and default values</h2>
<p>It's important to consider the way default values of attributes are applied. There is often a difference between simply using dot notation to assign a value and using <code>Object.defineProperty()</code>, as shown in the example below.</p>
<pre class="brush: js">
var o = {};

o.a = 1;
// is equivalent to :
Object.defineProperty(o, "a", {value : 1,
                               writable : true,
                               configurable : true,
                               enumerable : true});


// On the other hand,
Object.defineProperty(o, "a", {value : 1});
// is equivalent to :
Object.defineProperty(o, "a", {value : 1,
                               writable : false,
                               configurable : false,
                               enumerable : false});
</pre>
<h2 id="Cross-browser_concerns">Cross-browser concerns</h2>
<h3 id="Redefining_the_length_property_of_an_Array_object">Redefining the length property of an Array object</h3>
<p>It is possible to redefine the <code>length</code> property of arrays, but not all browsers permit this redefinition. &nbsp;Firefox 4 will throw a <code>TypeError</code> on any attempt to redefine the length property of an array. &nbsp;Versions of Chrome which implement <code>Object.defineProperty()</code> in some circumstances ignore a length value different from the array's current <code>length</code> property, and changing writability seems to silently not work in some circumstances. &nbsp;Versions of Safari which implement <code>Object.defineProperty()</code> ignore a length value different from the array's current <code>length</code> property, and attempts to change writability execute without error but do not actually change the property's writability. &nbsp;Only Internet Explorer 9 and later appear to fully and correctly implement redefinition of the <code>length</code> property of arrays. &nbsp;For now, don't rely on redefining the <code>length</code> property of an array to either work, or to work in a particular manner.</p>
<h3 id="Internet_Explorer_8_specific_case">Internet Explorer 8 specific case</h3>
<p>Internet Explorer 8 implemented a <code>Object.defineProperty()</code> method that could <a class="external" href="http://msdn.microsoft.com/en-us/library/dd229916%28VS.85%29.aspx">only be used on DOM objects</a>. A few things need to be noted:</p>
<ul>
  <li>Trying to use <code>Object.defineProperty()</code> on native objects throws an error.</li>
  <li>Property attributes must be set to some values. <code>true, true, true</code> for data descriptor and <code>true</code> for configurable, <code>false</code> for enumerable for accessor descriptor.(?) Any attempt to provide other value(?) will result in an error being thrown.</li>
  <li>Reconfiguring a property requires first deleting the property. If the property isn't deleted, it stays as it was before the reconfiguration attempt.</li>
</ul>
<h3 id="Browser_compatibility">Browser compatibility</h3>
<p>{{ CompatibilityTable() }}</p>
<div id="compat-desktop">
  <table class="compat-table">
    <tbody>
      <tr>
        <th>Feature</th>
        <th>Firefox (Gecko)</th>
        <th>Chrome</th>
        <th>Internet Explorer</th>
        <th>Opera</th>
        <th>Safari</th>
      </tr>
      <tr>
        <td>Basic support</td>
        <td>4 (2)</td>
        <td>5 (previous versions untested)</td>
        <td>9 (8, but only on DOM objects and with some non-standard behaviors. <a href="#ie8-specific">See above</a>.)</td>
        <td>11.60</td>
        <td>5.1 (5, but not on DOM objects)</td>
      </tr>
    </tbody>
  </table>
</div>
<div id="compat-mobile">
  <table class="compat-table">
    <tbody>
      <tr>
        <th>Feature</th>
        <th>Firefox Mobile (Gecko)</th>
        <th>Android</th>
        <th>IE Mobile</th>
        <th>Opera Mobile</th>
        <th>Safari Mobile</th>
      </tr>
      <tr>
        <td>Basic support</td>
        <td>{{ CompatGeckoMobile("2") }}</td>
        <td>{{ CompatVersionUnknown() }}</td>
        <td>{{ CompatUnknown() }}</td>
        <td>11.50</td>
        <td>{{ CompatVersionUnknown() }}</td>
      </tr>
    </tbody>
  </table>
</div>
<p>Based on <a class="external" href="http://kangax.github.com/es5-compat-table/">Kangax's compat tables</a>.</p>
<h2 id="See_also">See also</h2>
<ul>
  <li><a href="/en-US/docs/Enumerability_and_ownership_of_properties" title="/en-US/docs/Enumerability_and_ownership_of_properties">Enumerability and ownership of properties</a></li>
  <li><code><a href="/en/JavaScript/Reference/Global_Objects/Object/defineProperties" title="en/JavaScript/Reference/Global_Objects/Object/defineProperties">Object.defineProperties()</a></code></li>
  <li><code><a href="/en/JavaScript/Reference/Global_Objects/Object/propertyIsEnumerable" title="/en/JavaScript/Reference/Global_Objects/Object/propertyIsEnumerable">Object.propertyIsEnumerable()</a></code></li>
  <li><code><a href="/en/JavaScript/Reference/Global_Objects/Object/watch" title="en/JavaScript/Reference/Global_Objects/Object/watch">object.watch()</a></code></li>
  <li><code><a href="/en/JavaScript/Reference/Global_Objects/Object/unwatch" title="en/JavaScript/Reference/Global_Objects/Object/unwatch">object.unwatch()</a></code></li>
  <li><code><a href="/en/JavaScript/Reference/Operators/get" title="en/JavaScript/Reference/Operators/get">get</a></code></li>
  <li><code><a href="/en/JavaScript/Reference/Operators/set" title="en/JavaScript/Reference/Operators/set">set</a></code></li>
  <li><code><a href="/en/JavaScript/Reference/Global_Objects/Object/create" title="en/JavaScript/Reference/Global Objects/Object/create">Object.create()</a></code></li>
  <li><a href="/en/JavaScript/Reference/Global_Objects/Object/defineProperty/Additional_examples" title="en/JavaScript/Reference/Global_Objects/Object/defineProperty/Additional_examples">Additional <code>Object.defineProperty</code> examples</a></li>
</ul>
<p>{{ languages( {"zh-cn": "zh-cn/JavaScript/Reference/Global_Objects/Object/defineProperty" } ) }}</p>
Revert to this revision