Table of contents
- 1.1. Summary
- 1.2. Syntax
- 1.3. Parameters
- 1.4. Description
- 2. Browser compatibility
- 3. See also
Introduced in JavaScript 1.8.5
Summary
Defines new or modifies existing properties directly on an object, returning the object.
Method of Object | |
|---|---|
| Implemented in | JavaScript 1.8.5 |
| ECMAScript Edition | ECMAScript 5th Edition |
Syntax
Object.defineProperties(obj, props)
Parameters
- obj
- The object on which to define or modify properties.
- props
- An object whose own enumerable properties constitute descriptors for the properties to be defined or modified.
Description
Object.defineProperties, in essence, defines all properties corresponding to the enumerable own properties of props on the object objrops object.
Assuming a pristine execution environment with all names and properties referring to their initial values, Object.defineProperties is almost completely equivalent (note the comment in isCallable) to the following reimplementation in JavaScript:
function defineProperties(obj, properties)
{
function convertToDescriptor(desc)
{
function hasProperty(obj, prop)
{
return Object.prototype.hasOwnProperty.call(obj, prop);
}
function isCallable(v)
{
// NB: modify as necessary if other values than functions are callable.
return typeof v === "function";
}
if (typeof desc !== "object" || desc === null)
throw new TypeError("bad desc");
var d = {};
if (hasProperty(desc, "enumerable"))
d.enumerable = !!obj.enumerable;
if (hasProperty(desc, "configurable"))
d.configurable = !!obj.configurable;
if (hasProperty(desc, "value"))
d.value = obj.value;
if (hasProperty(desc, "writable"))
d.writable = !!desc.writable;
if (hasProperty(desc, "get"))
{
var g = desc.get;
if (!isCallable(g) && g !== "undefined")
throw new TypeError("bad get");
d.get = g;
}
if (hasProperty(desc, "set"))
{
var s = desc.set;
if (!isCallable(s) && s !== "undefined")
throw new TypeError("bad set");
d.set = s;
}
if (("get" in d || "set" in d) && ("value" in d || "writable" in d))
throw new TypeError("identity-confused descriptor");
return d;
}
if (typeof obj !== "object" || obj === null)
throw new TypeError("bad obj");
properties = Object(properties);
var keys = Object.keys(properties);
var descs = [];
for (var i = 0; i < keys.length; i++)
descs.push([keys[i], convertToDescriptor(properties[keys[i]])]);
for (var i = 0; i < descs.length; i++)
Object.defineProperty(obj, descs[i][0], descs[i][1]);
return obj;
}
Browser compatibility
Based on Kangax's compat tables.
| Feature | Firefox (Gecko) | Chrome | Internet Explorer | Opera | Safari |
|---|---|---|---|---|---|
| Basic support | 4 (2) | 5 (previous versions untested) | 9 | -- | 5 |
| Feature | Firefox Mobile (Gecko) | Android | IE Mobile | Opera Mobile | Safari Mobile |
|---|---|---|---|---|---|
| Basic support | ? | ? | ? | ? | ? |