Object.defineProperty()
Baseline
Widely available
This feature is well established and works across many devices and browser versions. Itâs been available across browsers since 2015å¹´7æ.
éæ
æ¹æ³ Object.defineProperty() æç´æ¥å°ä¸åç©ä»¶å®ç¾©ãææ¯ä¿®æ¹ç¾æç屬æ§ãå·è¡å¾æåå³å®ç¾©å®çç©ä»¶ã
å註ï¼éåæ¹æ³æç´æ¥éå° Object å¼å«å»ºæ§åï¼constructorï¼ï¼è䏿¯ Object åå¥ç實ä¾ã
å試ä¸ä¸
const object1 = {};
Object.defineProperty(object1, "property1", {
value: 42,
writable: false,
});
object1.property1 = 77;
// Throws an error in strict mode
console.log(object1.property1);
// Expected output: 42
èªæ³
Object.defineProperty(obj, prop, descriptor)
忏
obj-
è¦å®ç¾©å±¬æ§çç©ä»¶ã
prop-
è¦è¢«å®ç¾©æä¿®æ¹ç屬æ§ååã
descriptor-
è¦å®ç¾©æä¿®æ¹ç©ä»¶æè¿°å §å®¹ã
åå³å¼
被å®ç¾©å®æä¿®æ¹å®å±¬æ§çç©ä»¶ã
æè¿°
éåå½å¼å¯ä»¥ç¨ä¾å¢å æä¿®æ¹ç©ä»¶ä¸ç屬æ§å®ç¾©ãå¨ç©ä»¶å»ºç«å±¬æ§å¾ï¼éäºå±¬æ§åææè¢«è¨å®é è¨çè¨å®ï¼æè½è®éäºå±¬æ§è¢«åèãæ¹è®ååªé¤ãèéåå½å¼å¯ä»¥ç¨ä¾æ¹è®éäºé è¨çè¨å®ãæ ¹æé è¨ï¼è¢«å å°ç©ä»¶ä¸ä½¿ç¨Object.defineProperty()çå¼é½æ¯Immutableã
ç©ä»¶å §çå±¬æ§æè¿°å¨ï¼Property descriptorï¼ä¸»è¦æå ©ç¨®ï¼è³ææè¿°å¨ï¼data descriptorï¼è訪åæè¿°å¨ï¼accessor descriptorï¼ãè³ææè¿°å¨ï¼data descriptorï¼æ¯å¯ä»¥é¸æè½å¦è¦å¯«ç屬æ§ã訪åæè¿°å¨ï¼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.
data å accessor descriptors ççºç©ä»¶ï¼å ©è å ±äº«ä¸é¢æåç keyï¼
configurable-
trueåè¥ä¸å¯è¥æ¤å±¬æ§åå°å¯æ¹è®æåªé¤èªç¸æç©ä»¶ã é è¨çºfalse enumerable-
true妿ä¸å¯è¥ç¸æç©ä»¶è¢«åèï¼å°æåèæ¤å±¬æ§ã é è¨çºfalse
ä¸å data descriptor éæä»¥ä¸å¯é¸ç keyï¼
value-
The value associated with the property. Can be any valid JavaScript value (number, object, function, etc). é è¨
undefined. writable-
trueå該ç©ä»¶å±¬æ§å¯éé賦äºéç®åæ¹è®å ¶å¼ã é è¨false
ä¸å accessor descriptor 乿æä¸è¿°ä¹ optional keys:
get-
ä½çº getter å½¢å¼ï¼çºå±¬æ§åå¨çå½å¼ï¼å¦ææ²æ getter ç話ååå³
undefinedãå½å¼åå³å°ç¨æ¼å±¬æ§å¼ã é è¨undefined set-
ä½çº setter å½¢å¼ï¼çºå±¬æ§åå¨çå½å¼ï¼å¦ææ²æ setter ç話ååå³
undefinedã The function will receive as only argument the new value being assigned to the property. é è¨undefined
è«æ³¨æï¼éäºé¸é
並ä¸ä¸å®è¦æ¯ descriptor 屬æ§ï¼ç±ååéï¼prototype chainï¼ç¹¼æ¿ç屬æ§ï¼ä¹æè¢«èæ
®å°ãè¦ç¢ºä¿éè¦åçµï¼freezeï¼ç Object.prototype upfront é è¨è½è¢«ä¿åï¼è«æç¢ºæå®ææé¸é
ï¼ææ Object.prototype.__proto__ å±¬æ§æå nullã
// using __proto__
var obj = {};
Object.defineProperty(obj, "key", {
__proto__: null, // no inherited properties
value: "static", // not enumerable
// not configurable
// not writable
// as defaults
});
// being explicit
Object.defineProperty(obj, "key", {
enumerable: false,
configurable: false,
writable: false,
value: "static",
});
// recycling same object
function withValue(value) {
var d =
withValue.d ||
(withValue.d = {
enumerable: false,
writable: false,
configurable: false,
value: null,
});
d.value = value;
return d;
}
// ... and ...
Object.defineProperty(obj, "key", withValue("static"));
// if freeze is available, prevents adding or
// removing the object prototype properties
// (value, get, set, enumerable, writable, configurable)
(Object.freeze || Object)(Object.prototype);
ç¯ä¾
If you want to see how to use the Object.defineProperty method with a binary-flags-like syntax, see additional examples.
建ç«å±¬æ§
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.
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 = 38;
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
ä¿®æ¹å±¬æ§
å¦æè©²å±¬æ§å·²ç¶åå¨, Object.defineProperty() å°ææ ¹ææè¿°ç¬¦å
§çå¼åç©ä»¶ç¶åç configuration ä¾ä¿®æ¹å±¬æ§ã 妿èçæè¿°ç¬¦ä¹ configurable çç¹å¾µçº false (屬æ§çº ãnon-configurableã), é£é¤äº writable ä¹å¤çç¹å¾µé½å°ç¡æ³ä¿®æ¹ã å¨éåæ
æ³ï¼ä¹ä¸å¯è½å¨ data å accessor 屬æ§é¡åä¸ä¾ååæã
妿æä¸åå±¬æ§æ¯ non-configurable, é£å®ç writable ç¹å¾µåªè½è¢«æ¹è®çº false.
è¥å試æ¹è® non-configurable property attributesï¼å°æä¸åºä¸å TypeErrorï¼é¤éç¶åä¹å¼èæ°å¼ç¸åã
Writable attribute
ç¶ writable 屬æ§ç¹å¾µè¢«è¨çº false, æ¤å±¬æ§çº ãnon-writableã. å®å°ç¡æ³è¢«éæ°è³¦å¼ã
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.
å¯åè attribute
The enumerable property attribute defines whether the property shows up in a for...in loop and Object.keys() or not.
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
å¯è¨å® 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.
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.
æ°å¢å¤å屬æ§å賦äºåå§å¼
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,
});
Custom Setters and Getters
Example below shows how to implement a self-archiving object. When temperature property is set, the archive array gets a log entry.
function Archiver() {
var temperature = null;
var archive = [];
Object.defineProperty(this, "temperature", {
get: function () {
console.log("get!");
return temperature;
},
set: function (value) {
temperature = value;
archive.push({ val: temperature });
},
});
this.getArchive = function () {
return archive;
};
}
var arc = new Archiver();
arc.temperature; // 'get!'
arc.temperature = 11;
arc.temperature = 13;
arc.getArchive(); // [{ val: 11 }, { val: 13 }]
or
var pattern = {
get: function () {
return "I always return this string, whatever you have assigned";
},
set: function () {
this.myname = "this is my name string";
},
};
function TestDefineSetAndGet() {
Object.defineProperty(this, "myproperty", pattern);
}
var instance = new TestDefineSetAndGet();
instance.myproperty = "test";
console.log(instance.myproperty); // I always return this string, whatever you have assigned
console.log(instance.myname); // this is my name string
è¦æ ¼
| Specification |
|---|
| ECMAScript® 2027 Language Specification> # sec-object.defineproperty> |
ç覽å¨ç¸å®¹æ§
Compatibility notes
>Redefining the length property of an Array object
It is possible to redefine the length property of arrays, subject to the usual redefinition restrictions. (The length property is initially non-configurable, non-enumerable, and writable. Thus on an unaltered array, it's possible to change the length property's value or to make it non-writable. It is not allowed to change its enumerability or configurability, or if it is non-writable to change its value or writability.) However, not all browsers permit this redefinition.
Firefox 4 through 22 will throw a TypeError on any attempt whatsoever (whether permitted or not) 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. In some circumstances changing writability seems to silently not work (and not throw an exception). Also, relatedly, some array-mutating methods like Array.prototype.push don't respect a non-writable length.
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, and Firefox 23 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. And even when you can rely on it, there's really no good reason to do so.
Internet Explorer 8 specific notes
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. The
configurable,enumerableandwritableattributes should all be set totruefor data descriptor andtrueforconfigurable,falseforenumerablefor 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.