前端重新开始-Object.defineProperty

92 阅读1分钟

参考Mdn上Object.defineProperty

Syntax 语法

Object.defineProperty(obj, prop, descriptor)

Parameters 参数

obj

The object on which to define the property.

prop

The name or Symbol of the property to be defined or modified.

descriptor

The descriptor for the property being defined or modified.

return

The object that was passed to the function.

descriptor解释说明

  • [configurable=false] 是否允许修改配置

if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object.

  • [enumerable=false] 是否允许遍历当前属性

if and only if this property shows up during enumeration of the properties on the corresponding object.

  • [value=undefined] 默认值

The value associated with the property. Can be any valid JavaScript value (number, object, function, etc).

  • [writable=false] 是否允许通过assignment operator 操作修改指定值

if the value associated with the property may be changed with an assignment operator.

  • [get=undefined] 类型computed 的get方法

A function which serves as a getter for the property, or undefined if there is no getter. When the property is accessed, this function is called without arguments and with this set to the object through which the property is accessed (this may not be the object on which the property is defined due to inheritance). The return value will be used as the value of the property.

  • [set=undefined] 类似computed 的set 方法

A function which serves as a setter for the property, or undefined if there is no setter. When the property is assigned, this function is called with one argument (the value being assigned to the property) and with this set to the object through which the property is assigned.

注意事项

If a descriptor has neither of 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.

如果descriptor 没有value, writable, get 和 set 这些关键字的时候,它只是被当作是普通的描述来处理; 如果包含value/writable 和 get/set 的关键字组合的话,会有一个报错(简单来说就是不能同时使用这种组合)