defineProperty

Introduced in JavaScript 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), 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. All descriptors regardless of flavor include the configurable and enumerable fields.

A property descriptor is an object with the following fields:

value
The value associated with the property. (data descriptors only). Defaults to undefined.
writable
True if and only if the value associated with the property may be changed. (data descriptors only). Defaults to false.
get
A function which serves as a getter for the property, or undefined if there is no getter. (accessor descriptors only). Defaults to undefined.
set
A function which serves as a setter for the property, or undefined if there is no setter. (accessor descriptors only). Defaults to undefined.
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.

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.

Example

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

You can use the Object.defineProperty method with native objects also. The following example shows how to implement the HTMLSelectElement's selectedIndex property in radio button groups.

<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Radio group selectedIndex example</title>
<script type="text/javascript">
Object.defineProperty(NodeList.prototype, "selectedIndex", {
	get: function() {
		var nIndex = this.length - 1;
		while (nIndex > -1 && !this[nIndex].checked) { nIndex--; }
		return nIndex;
	},
	set: function(nNewIndex) {
		if (isNaN(nNewIndex)) { return; }
		var nOldIndex = this.selectedIndex;
		if (nOldIndex > -1) { this[nOldIndex].checked = false; }
		if (nNewIndex > -1) { this[nNewIndex].checked = true; }
	},
	enumerable : true,
	configurable : false
});

// try it!
function checkForm() {
	var nSelectedIndex = document.myForm.myRadioGroup.selectedIndex;
	if (nSelectedIndex < 0) { alert("Select a gadget!!"); return false; }
	alert("Congratulations!! You selected the " + document.myForm.myRadioGroup[nSelectedIndex].value + ".");
	return true;
}
</script>

</head>

<body>
						
<form name="myForm" onsubmit="return(checkForm());">
<fieldset><legend>Select a gadget</legend>
<p><input type="radio" name="myRadioGroup" id="ourShirt" value="shirt" /> <label for="ourShirt">shirt</label><br />
<input type="radio" name="myRadioGroup" id="ourPants" value="pants" /> <label for="ourPants">pants</label><br />
<input type="radio" name="myRadioGroup" id="ourBelt" value="belt" /> <label for="ourBelt">belt</label><br />
<input type="radio" name="myRadioGroup" id="ourShoes" value="shoes" /> <label for="ourShoes">shoes</label></p>
<p><span style="cursor:pointer;text-decoration:underline;color:#0000ff;" onclick="document.myForm.myRadioGroup.selectedIndex=2;">Select our favorite gadget ;-)</span></p>
<p><input type="submit" value="Order!" />
</fieldset>
</form>
</body>
</html>

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 current configuration. If the old descriptor had its configurable attribute set to false (the property is said "non-configurable"), then no attribute besides writable can be changed. In that case, it is also not possible to switch back and forth from data/accessor properties type (a property which would have been defined without get/set/value/writable is called "generic" and is "typed" as a data descriptor).

A TypeError is thrown when non-configurable property attributes are changed unless it's the writable attribute or if the current and new values are equal.

Writable attribute

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

Example

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

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

alert(o.a); // alerts 37
o.a = 25;
alert(o.a); // alerts 37. The assignment didn't work. No error thrown

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 or not.

Example

var i;
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;

for (i in o) {    
    alert(i);  
}
// alerts 'a' then 'd'

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

alert(o.a); // alerts 1
delete o.a; // Nothing happens
alert(o.a); // alerts 1

If o.a configurable attribute was true, none of the error would be thrown and the property would be deleted at the end.

Difference with usual property addition and default values

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});

Code considerations

If you have to define many properties through the Object.defineProperty method, you can utilise the same descriptor object for each property, redefining it from time to time through binary flags.

Examples

var oDesc = {};
function setProp (nMask, oObj, sKey, vVal_fGet, fSet) {
	if (nMask & 12) {
		if (arguments.length > 3) { oDesc.value = vVal_fGet; } else { delete oDesc.value; }
		oDesc.writable = Boolean(nMask & 8);
		delete oDesc.get;
		delete oDesc.set;
	} else {
		if (vVal_fGet) { oDesc.get = vVal_fGet; } else { delete oDesc.get; }
		if (fSet) { oDesc.set = fSet; } else { delete oDesc.set; }
		delete oDesc.value;
		delete oDesc.writable;
	}
	oDesc.enumerable = Boolean(nMask & 1);
	oDesc.configurable = Boolean(nMask & 2);
	Object.defineProperty(oObj, sKey, oDesc);
}

/**
*	:: function setProp ::
*
*	vVal_fGet is the value to assign to a data descriptor or the getter function to assign to an accessor descriptor;
*
*	nMask is a bitmask:
*
*	flag 0x1: property is enumerable,
*	flag 0x2: property is configurable,
*	flag 0x4: property is data descriptor,
*	flag 0x8: property is writable.
*	Note: If flag 0x8 is setted to "writable", the propery will be considered a data descriptor even if the flag 0x4 is setted to "accessor descriptor"!
*
*	Values:
*
*	0  : accessor descriptor - not configurable, not enumerable (0000).
*	1  : accessor descriptor - not configurable, enumerable (0001).
*	2  : accessor descriptor - configurable, not enumerable (0010).
*	3  : accessor descriptor - configurable, enumerable (0011).
*	4  : readonly data descriptor - not configurable, not enumerable (0100).
*	5  : readonly data descriptor - not configurable, enumerable (0101).
*	6  : readonly data descriptor - configurable, not enumerable (0110).
*	7  : readonly data descriptor - configurable, enumerable (0111).
*	8  : writable data descriptor - not configurable, not enumerable (1000).
*	9  : writable data descriptor - not configurable, enumerable (1001).
*	10 : writable data descriptor - configurable, not enumerable (1010).
*	11 : writable data descriptor - configurable, enumerable (1011).
*/

// creating a new empty object
var myObj = {};

// adding a writable data descriptor - not configurable, not enumerable
setProp(8, myObj, "myNumber", 25);

// adding a readonly data descriptor - not configurable, enumerable
setProp(5, myObj, "myString", "Hello world!");

// adding an accessor descriptor - not configurable, enumerable
setProp(1, myObj, "myArray", function() {
	for (var iBit = 0, iFlag = 1, aBoolArr = [false]; iFlag < this.myNumber + 1 || (this.myNumber & iFlag); iFlag = iFlag << 1) { aBoolArr[iBit++] = Boolean(this.myNumber & iFlag); }
	return aBoolArr;
}, function(aNewMask) {
	for (var nNew = 0, iBit = 0; iBit < aNewMask.length; iBit++) { nNew |= Boolean(aNewMask[iBit]) << iBit; }
	this.myNumber = nNew;
});

// adding a writable data descriptor (undefined value) - configurable, enumerable
setProp(11, myObj, "myUndefined");

// adding an accessor descriptor (only getter) - not configurable, enumerable
setProp(1, myObj, "myDate", function() { return new Date(); });

// adding an accessor descriptor (only setter) - not configurable, not enumerable
setProp(0, myObj, "myAlert", null, function(sTxt) { alert(sTxt); });

myObj.myAlert = myObj.myDate.toLocaleString() + "\n\n" + myObj.myString + "\nThe number " + myObj.myNumber + " represents the following bitmask: " + myObj.myArray.join(", ") + ".";

You can do the same thing with an anonymous descriptor object.

new (function() {
	function buildProp (nMask, oObj, sKey, vVal_fGet, fSet) {
		if (nMask & 12) {
			if (arguments.length > 3) { this.value = vVal_fGet; } else { delete this.value; }
			this.writable = Boolean(nMask & 8);
			delete this.get;
			delete this.set;
		} else {
			if (vVal_fGet) { this.get = vVal_fGet; } else { delete this.get; }
			if (fSet) { this.set = fSet; } else { delete this.set; }
			delete this.value;
			delete this.writable;
		}
		this.enumerable = Boolean(nMask & 1);
		this.configurable = Boolean(nMask & 2);
		Object.defineProperty(oObj, sKey, this);
	};
	buildProp(5, window, "setProp", buildProp);
})();

// creating a new empty object
var myObj = {};

// adding a writable data descriptor - not configurable, not enumerable
setProp(8, myObj, "myNumber", 25);

// adding a readonly data descriptor - not configurable, enumerable
setProp(5, myObj, "myString", "Hello world!");
// etc. etc.

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 IE9 appears 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

IE8 implemented a Object.defineProperty() method that could only be used on DOM objects. A couple of 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 to delete the property first. If the property isn't deleted, it stays as it was before the reconfiguration attempt.

Browser compatibility

  • Desktop
  • Mobile

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.) -- 5.1 (5, but not on DOM objects)
Feature Firefox Mobile (Gecko) Android IE Mobile Opera Mobile Safari Mobile
Basic support ? ? ? ? ?

Based on Kangax's compat tables.

See also

Tags (3)

Edit tags

Attachments (0)

 

Attach file