Object.defineProperty()

Object.defineProperty() 静态方法直接在对象上定义新属性,或修改对象上的现有属性,并返回该对象。

¥The Object.defineProperty() static method defines a new property directly on an object, or modifies an existing property on an object, and returns the object.

Try it

语法

¥Syntax

js
Object.defineProperty(obj, prop, descriptor)

参数

¥Parameters

obj

要定义属性的对象。

prop

一个字符串或 Symbol,指定要定义或修改的属性的键。

descriptor

正在定义或修改的属性的描述符。

返回值

¥Return value

传递给函数的对象,添加或修改了指定的属性。

¥The object that was passed to the function, with the specified property added or modified.

描述

¥Description

Object.defineProperty() 允许精确添加或修改对象的属性。通过 assignment 的正常属性添加会创建在属性枚举期间显示的属性(for...inObject.keys() 等),其值可能会更改并且可能是 deleted。此方法允许更改这些额外详细信息的默认值。默认情况下,使用 Object.defineProperty() 添加的属性不可写、不可枚举且不可配置。此外,Object.defineProperty() 使用 [[DefineOwnProperty]] 内部方法,而不是 [[Set]],因此它不会调用 setters,即使该属性已经存在。

¥Object.defineProperty() allows a 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, Object.keys(), etc.), whose values may be changed and which may be deleted. This method allows these extra details to be changed from their defaults. By default, properties added using Object.defineProperty() are not writable, not enumerable, and not configurable. In addition, Object.defineProperty() uses the [[DefineOwnProperty]] internal method, instead of [[Set]], so it does not invoke setters, even when the property is already present.

对象中存在的属性描述符有两种主要风格:数据描述符和访问器描述符。数据描述符是一个属性,其值可能是可写的,也可能是不可写的。访问器描述符是由一对 getter-setter 函数描述的属性。描述符必须是这两种风格之一;不可能两者兼而有之。

¥Property descriptors present in objects come in two main flavors: data descriptors and accessor descriptors. A data descriptor is a property with a value that 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.

数据和访问器描述符都是对象。它们共享以下可选键(请注意:这里提到的默认值是在使用 Object.defineProperty() 定义属性的情况下):

¥Both data and accessor descriptors are objects. They share the following optional keys (please note: the defaults mentioned here are in the case of defining properties using Object.defineProperty()):

configurable

当设置为 false 时,

  • 该属性的类型不能在数据属性和访问器属性之间更改,并且
  • 该属性不得被删除,并且
  • 其描述符的其他属性不能更改(但是,如果是 writable: true 的数据描述符,则可以更改 value,并且可以将 writable 更改为 false)。

默认为 false

enumerable

true 当且仅当该属性在相应对象的属性枚举过程中出现时。默认为 false

数据描述符还具有以下可选键:

¥A data descriptor also has the following optional keys:

value

与属性关联的值。可以是任何有效的 JavaScript 值(数字、对象、函数等)。默认为 undefined

writable

如果与属性关联的值可以通过 赋值运算符 更改,则为 true。默认为 false

访问器描述符还具有以下可选键:

¥An accessor descriptor also has the following optional keys:

get

充当属性的 getter 的函数,如果没有 getter,则为 undefined。当访问属性时,调用此函数时不带参数,并将 this 设置为访问属性的对象(由于继承,这可能不是定义属性的对象)。返回值将用作属性的值。默认为 undefined

set

充当属性 setter 的函数,如果没有 setter,则为 undefined。分配属性时,将使用一个参数(分配给属性的值)调用此函数,并将 this 设置为分配属性的对象。默认为 undefined

如果描述符没有任何 valuewritablegetset 键,则将其视为数据描述符。如果描述符同时具有 [valuewritable] 和 [getset] 键,则会引发异常。

¥If a descriptor doesn't have any of the value, writable, get, and set keys, it is treated as a data descriptor. If a descriptor has both [value or writable] and [get or set] keys, an exception is thrown.

这些属性不一定是描述符自己的属性。继承的属性也会被考虑。为了确保保留这些默认值,你可以预先冻结描述符对象原型链中的现有对象,显式指定所有选项,或者创建 null-原型对象

¥These attributes are not necessarily the descriptor's own properties. Inherited properties will be considered as well. In order to ensure these defaults are preserved, you might freeze existing objects in the descriptor object's prototype chain upfront, specify all options explicitly, or create a null-prototype object.

js
const obj = {};
// 1. Using a null prototype: no inherited properties
const descriptor = Object.create(null);
descriptor.value = "static";

// not enumerable, not configurable, not writable as defaults
Object.defineProperty(obj, "key", descriptor);

// 2. Being explicit by using a throw-away object literal with all attributes present
Object.defineProperty(obj, "key2", {
  enumerable: false,
  configurable: false,
  writable: false,
  value: "static",
});

// 3. Recycling same object
function withValue(value) {
  const d =
    withValue.d ||
    (withValue.d = {
      enumerable: false,
      writable: false,
      configurable: false,
      value,
    });

  // avoiding duplicate operation for assigning value
  if (d.value !== value) 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);

当属性已经存在时,Object.defineProperty() 尝试根据描述符中的值和属性的当前配置来修改属性。

¥When the property already exists, Object.defineProperty() attempts to modify the property according to the values in the descriptor and the property's current configuration.

如果旧描述符的 configurable 属性设置为 false,则该属性被认为是不可配置的。无法更改不可配置访问器属性的任何属性,并且无法在数据和访问器属性类型之间切换。对于具有 writable: true 的数据属性,可以修改值并将 writable 属性从 true 更改为 false。当尝试更改不可配置的属性(valuewritable 除外,如果允许)时,会抛出 TypeError,定义与数据属性的原始值相同的值时除外。

¥If the old descriptor had its configurable attribute set to false, the property is said to be non-configurable. It is not possible to change any attribute of a non-configurable accessor property, and it is not possible to switch between data and accessor property types. For data properties with writable: true, it is possible to modify the value and change the writable attribute from true to false. A TypeError is thrown when attempts are made to change non-configurable property attributes (except value and writable, if permitted), except when defining a value same as the original value on a data property.

当当前属性可配置时,将属性定义为 undefined 会有效地删除它。例如,如果 o.k 是访问器属性,则 Object.defineProperty(o, "k", { set: undefined }) 将删除 setter,使 k 只有 getter 并变为只读。如果新描述符中不存在某个属性,则保留旧描述符属性的值(不会隐式地将其重新定义为 undefined)。通过给出不同 "flavor" 的描述符,可以在数据和访问器属性之间切换。例如,如果新描述符是数据描述符(具有 valuewritable),则原始描述符的 getset 属性都将被删除。

¥When the current property is configurable, defining an attribute to undefined effectively deletes it. For example, if o.k is an accessor property, Object.defineProperty(o, "k", { set: undefined }) will remove the setter, making k only have a getter and become readonly. If an attribute is absent from the new descriptor, the old descriptor attribute's value is kept (it won't be implicitly re-defined to undefined). It is possible to toggle between data and accessor property by giving a descriptor of a different "flavor". For example, if the new descriptor is a data descriptor (with value or writable), the original descriptor's get and set attributes will both be dropped.

示例

¥Examples

创建属性

¥Creating a property

当指定的属性在对象中不存在时,Object.defineProperty() 将按所述创建一个新属性。描述符中可以省略字段,并且输入这些字段的默认值。

¥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 inputted.

js
const 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
let bValue = 38;
Object.defineProperty(o, "b", {
  get() {
    return bValue;
  },
  set(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() {
    return 0xdeadbeef;
  },
});
// throws a TypeError: value appears
// only in data descriptors,
// get appears only in accessor descriptors

修改属性

¥Modifying a property

修改现有属性时,当前属性配置确定操作符是否成功、不执行任何操作或抛出 TypeError

¥When modifying an existing property, the current property configuration determines if the operator succeeds, does nothing, or throws a TypeError.

可写属性

¥Writable attribute

writable 属性为 false 时,该属性被称为 "non-writable"。它不能被重新分配。尝试写入不可写属性不会更改它,并会导致 严格模式 中出现错误。

¥When the writable property attribute is false, the property is said to be "non-writable". It cannot be reassigned. Trying to write to a non-writable property doesn't change it and results in an error in strict mode.

js
const o = {}; // Creates a new object

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

console.log(o.a); // 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); // 37; the assignment didn't work

// strict mode
(() => {
  "use strict";
  const o = {};
  Object.defineProperty(o, "b", {
    value: 2,
    writable: false,
  });
  o.b = 3; // throws TypeError: "b" is read-only
  return o.b; // returns 2 without the line above
})();

枚举属性

¥Enumerable attribute

enumerable 属性定义了 Object.assign()spread 运算符是否考虑该属性。对于非 Symbol 属性,它还定义它是否显示在 for...in 循环和 Object.keys() 中。欲了解更多信息,请参阅 可枚举性和属性所有权

¥The enumerable property attribute defines whether the property is considered by Object.assign() or the spread operator. For non-Symbol properties, it also defines whether it shows up in a for...in loop and Object.keys() or not. For more information, see Enumerability and ownership of properties.

js
const 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
Object.defineProperty(o, Symbol.for("e"), {
  value: 5,
  enumerable: true,
});
Object.defineProperty(o, Symbol.for("f"), {
  value: 6,
  enumerable: false,
});

for (const i in o) {
  console.log(i);
}
// Logs 'a' and 'd' (always in that order)

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

o.propertyIsEnumerable("a"); // true
o.propertyIsEnumerable("b"); // false
o.propertyIsEnumerable("c"); // false
o.propertyIsEnumerable("d"); // true
o.propertyIsEnumerable(Symbol.for("e")); // true
o.propertyIsEnumerable(Symbol.for("f")); // false

const p = { ...o };
p.a; // 1
p.b; // undefined
p.c; // undefined
p.d; // 4
p[Symbol.for("e")]; // 5
p[Symbol.for("f")]; // undefined

可配置属性

¥Configurable attribute

configurable 属性控制是否可以从对象中删除该属性以及是否可以更改其属性(valuewritable 除外)。

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

此示例说明了不可配置的访问器属性。

¥This example illustrates a non-configurable accessor property.

js
const o = {};
Object.defineProperty(o, "a", {
  get() {
    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() {},
}); // throws a TypeError (set was undefined previously)
Object.defineProperty(o, "a", {
  get() {
    return 1;
  },
}); // throws a TypeError
// (even though the new get does exactly the same thing)
Object.defineProperty(o, "a", {
  value: 12,
}); // throws a TypeError
// ('value' can be changed when 'configurable' is false, but only when the property is a writable data property)

console.log(o.a); // 1
delete o.a; // Nothing happens; throws an error in strict mode
console.log(o.a); // 1

如果 o.aconfigurable 属性为 true,则不会抛出任何错误,并且最终会删除该属性。

¥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.

此示例说明了不可配置但可写的数据属性。属性的 value 仍然可以更改,writable 仍然可以从 true 切换到 false

¥This example illustrates a non-configurable but writable data property. The property's value can still be changed, and writable can still be toggled from true to false.

js
const o = {};
Object.defineProperty(o, "b", {
  writable: true,
  configurable: false,
});
console.log(o.b); // undefined
Object.defineProperty(o, "b", {
  value: 1,
}); // Even when configurable is false, because the object is writable, we may still replace the value
console.log(o.b); // 1
o.b = 2; // We can change the value with assignment operators as well
console.log(o.b); // 2
// Toggle the property's writability
Object.defineProperty(o, "b", {
  writable: false,
});
Object.defineProperty(o, "b", {
  value: 1,
}); // TypeError: because the property is neither writable nor configurable, it cannot be modified
// At this point, there's no way to further modify 'b'
// or restore its writability

此示例说明了可配置但不可写的数据属性。属性的 value 仍可以替换为 defineProperty(但不能使用赋值运算符),并且可以切换 writable

¥This example illustrates a configurable but non-writable data property. The property's value may still be replaced with defineProperty (but not with assignment operators), and writable may be toggled.

js
const o = {};
Object.defineProperty(o, "b", {
  writable: false,
  configurable: true,
});
Object.defineProperty(o, "b", {
  value: 1,
}); // We can replace the value with defineProperty
console.log(o.b); // 1
o.b = 2; // throws TypeError in strict mode: cannot change a non-writable property's value with assignment

此示例说明了不可配置且不可写的数据属性。无法更新属性的任何属性,包括其 value

¥This example illustrates a non-configurable and non-writable data property. There's no way to update any attribute of the property, including its value.

js
const o = {};
Object.defineProperty(o, "b", {
  writable: false,
  configurable: false,
});
Object.defineProperty(o, "b", {
  value: 1,
}); // TypeError: the property cannot be modified because it is neither writable nor configurable.

添加属性和默认值

¥Adding properties and default values

考虑属性默认值的应用方式非常重要。使用 属性访问器 赋值和使用 Object.defineProperty() 赋值之间通常存在差异,如下例所示。

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

js
const 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,
});

自定义 setter 和 getter

¥Custom setters and getters

下面的示例展示了如何实现自归档对象。当设置 temperature 属性时,archive 数组将获取一个日志条目。

¥The example below shows how to implement a self-archiving object. When temperature property is set, the archive array gets a log entry.

js
function Archiver() {
  let temperature = null;
  const archive = [];

  Object.defineProperty(this, "temperature", {
    get() {
      console.log("get!");
      return temperature;
    },
    set(value) {
      temperature = value;
      archive.push({ val: temperature });
    },
  });

  this.getArchive = () => archive;
}

const arc = new Archiver();
arc.temperature; // 'get!'
arc.temperature = 11;
arc.temperature = 13;
arc.getArchive(); // [{ val: 11 }, { val: 13 }]

在此示例中,getter 始终返回相同的值。

¥In this example, a getter always returns the same value.

js
const pattern = {
  get() {
    return "I always return this string, whatever you have assigned";
  },
  set() {
    this.myname = "this is my name string";
  },
};

function TestDefineSetAndGet() {
  Object.defineProperty(this, "myproperty", pattern);
}

const 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

属性继承

¥Inheritance of properties

如果继承了访问器属性,则当在后代对象上访问和修改该属性时,将调用其 getset 方法。如果这些方法使用变量来存储值,则该值将被所有对象共享。

¥If an accessor property is inherited, its get and set methods will be called when the property is accessed and modified on descendant objects. If these methods use a variable to store the value, this value will be shared by all objects.

js
function MyClass() {}

let value;
Object.defineProperty(MyClass.prototype, "x", {
  get() {
    return value;
  },
  set(x) {
    value = x;
  },
});

const a = new MyClass();
const b = new MyClass();
a.x = 1;
console.log(b.x); // 1

可以通过将该值存储在另一个属性中来解决此问题。在 getset 方法中,this 指向用于访问或修改属性的对象。

¥This can be fixed by storing the value in another property. In get and set methods, this points to the object which is used to access or modify the property.

js
function MyClass() {}

Object.defineProperty(MyClass.prototype, "x", {
  get() {
    return this.storedX;
  },
  set(x) {
    this.storedX = x;
  },
});

const a = new MyClass();
const b = new MyClass();
a.x = 1;
console.log(b.x); // undefined

与访问器属性不同,数据属性始终在对象本身上设置,而不是在原型上设置。但是,如果继承了不可写的数据属性,仍然会阻止在对象上对其进行修改。

¥Unlike accessor properties, data properties are always set on the object itself, not on a prototype. However, if a non-writable data property is inherited, it is still prevented from being modified on the object.

js
function MyClass() {}

MyClass.prototype.x = 1;
Object.defineProperty(MyClass.prototype, "y", {
  writable: false,
  value: 1,
});

const a = new MyClass();
a.x = 2;
console.log(a.x); // 2
console.log(MyClass.prototype.x); // 1
a.y = 2; // Ignored, throws in strict mode
console.log(a.y); // 1
console.log(MyClass.prototype.y); // 1

规范

Specification
ECMAScript Language Specification
# sec-object.defineproperty

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看