Home >Web Front-end >JS Tutorial >JavaScript object-oriented detailed analysis of property descriptors

JavaScript object-oriented detailed analysis of property descriptors

WBOY
WBOYforward
2022-05-27 17:29:371783browse

This article brings you relevant knowledge about javascript, which mainly introduces related issues about object-oriented, including attribute descriptors, data descriptors, access descriptors, etc. Let’s take a look at the content below. I hope it will be helpful to everyone.

JavaScript object-oriented detailed analysis of property descriptors

[Related recommendations: javascript video tutorial, web front-end

JavaScript object-oriented - properties Descriptor

JavaScript actually supports a variety of programming paradigms, including functional programming and object-oriented programming:

  • Objects in JavaScript are designed as an unordered set of attributes Collection , like a hip-hop table, consists of key and value;
  • key is an identifier name, and value can be any type, or other object or function type;
  • If the value is a function, then we can call it The method of the object;

1. How to create an object?

  • The most common way to create objects in the early days is to use the Object class, and use the new keyword to create an object, and then store the properties or methods into the object:
var obj = new Object()
obj.name = 'why'
console.log(obj.name, obj) // why { name: 'why' }
  • Later, for the sake of convenience, many developers created objects directly in the form of literals:
// 字面量方式
var obj2 = { name: 'jam', age: '8' }
console.log(obj) // { name: 'jam', age: '8' }

2. Manipulate the properties of the object - property descriptor

Before, our properties were directly defined inside the object, or added directly to the object;
But in this way we cannot impose some restrictions on this property: for example, whether this property can be passed delect Can deletion be traversed during for-in traversal?
If we want to control an attribute more accurately, then I can use Attribute descriptor. The properties of an object can be accurately added or modified through property descriptors;
Property descriptors require the use of Object.defineProperty to add or modify properties.

Attribute descriptors are divided into two types: data descriptors and access descriptors

2.1 Data descriptors

A data descriptor is a property with a value that may or may not be writable. The data descriptor has the following optional key values:

  • value: The value corresponding to this attribute. Can be any valid JavaScript value (numeric value, object, function, etc.). The default is undefined.
  • writable: If and only if the writable of this attribute is true, the value can be changed by the copy operator. The default is false.
  • configurable: If and only if the attribute's configurable is true, the attribute descriptor can be changed, and the attribute can also be deleted from the corresponding object. The default is false.
  • enumerable: If and only if the enumerable of the property is true, the property can appear in the enumeration property of the object. The default is false.

2.2.1. Get the property descriptor Object.getOwnPropertyDescriptor()

The Object.getOwnPropertyDescriptor() method returns the property corresponding to the own property on the specified object. Property descriptor.

Object.getOwnPropertyDescriptor(obj,prop)
  • obj: The target object to be found
  • prop: The name of the property in the target object (String type).
  • Return value: If the specified property exists on the object, return its property descriptor object, otherwise return undefined.

Note: If the first parameter of this method is not an object, an error (TypeError) will be reported.

2.1.2. Set the property descriptor Object.defineProperty

The Object.defineProperty() method will directly define a new property on an object, or Modifies an existing property of an object and returns the object.

Object.defineProperty(obj,prop,descriptor)
  • obj: The object on which the properties are to be defined.
  • prop: The name of the property to be defined or modified.
  • descriptor: the property descriptor that will be defined or modified
  • Return value: the object passed to the function
如下示例代码展示了属性描述符的设置和获取
var obj = {
    name: 'jam',
    age: 8
}
Object.defineProperty(obj, 'job', {
    value: '律师'
})
console.log(Object.getOwnPropertyDescriptor(obj, 'age')) // { value: 8, writable: true, enumerable: true, configurable: true }

console.log(obj.job) // 律师
// 通过defineProperty新增的属性,该新属性是不可修改、不可删除以及不可枚举的
console.log(Object.getOwnPropertyDescriptor(obj, 'job')) // {value: '律师',writable: false,enumerable: false,configurable: false}

Note: Properties added through defineProperty are non-modifiable, non-deletable and non-enumerable

(1) Whether configurable can be deleted on the object

var obj = {
    name: 'jam',
    age: 8
}
Object.defineProperty(obj, 'address', {
    value: '河北',
    // configurable 该属性不可删除,更不可再次使用defineProperty修改属性描述符
    configurable: false,

})
delete obj.address // 想使用delete删除该属性
obj.address = '广州' // 想修改obj中的属性address值为广州
console.log(obj.address)  // 输出结果:河北

Because the attribute descriptor configurable value is false and cannot be deleted or modified, neither delete nor modification takes effect

(2) Whether enumerable can be enumerated and traversed

var obj = {
    name: 'jam',
    age: 8}Object.defineProperty(obj, 'sex ', {
    value: '男',
    // enumerable 配置该属性是否可以枚举
    enumerable: true})for (i in obj) {
    console.log(i)}

When enumerable: false, the output result is name age
When enumerable: true, the output result is name age sex

(3) writable This feature controls whether the attribute can be assigned a value (write a value)

var obj = {
    name: 'jam',
    age: 8}Object.defineProperty(obj, 'score', {
    value: 80,
    // writable: true 
    writable: false})obj.score = 100 console.log(obj.score) // 80

Because the value of writeable is false, when the score is modified to 100, the modification is not successful. The final output is 80

2.1.3、同时设置多个属性描述符 Object.defineProperties

是不是感觉每次只能设置一个属性的属性描述符很繁琐,Object.defineProperties可以帮你解决问题。
Object.defineProperties()方法为对象定义一个或多个新属性或修改现有属性,并返回该对象。

Object.defineProperties(obj,props)
  • obj:要在其上定义属性的对象。
  • props:要定义其可枚举属性或修改的属性描述符的对象。
  • 返回值:被传递给函数的对象。

示例代码如下:

var obj = {
    name: 'jam',}Object.defineProperties(obj, {
    'age': {
        value: 28,
        writable: true,
        configurable: false,
        enumerable: true
    },
    'job': {
        value: '律师',
        writable: true,
        configurable: false,
        enumerable: true
    },
    'sex': {
        value: '男',
        writable: false,
        configurable: false,
        enumerable: true
    },
    'height': {
        value: '1.8 m',
        writable: false,
        configurable: false,
        enumerable: true
    }})console.log(obj) //  name: 'jam', age: 28, job: '律师', sex: '男', height: '1.8m' }

2.2存取描述符

存取描述符是由getter-setter函数对描述的属性。存取描述符具有以下可选键值:

  • get:给属性提供getter的方法,如果没有getter则为undefined。当访问该属性时,该方法会被执行,方法执行时没有参数传入,但是会传入this对象。
  • set:给属性提供setter的方法,如果没有setter则为undefined。当属性值修改时,触发执行该方法。该方法将接受唯一参数,即该属性新的参数值。
  • configurable:当且仅当该属性的configurable为true时,该属性描述符才能够被改变,同时该属性也能从对应的对象上被删除。默认为false。
  • enurnerable:当且仅当该属性的enurnerable为true时,该属性才能够出现在对象的枚举属性中。默认为false。

configurable 和 enurnerable 的使用与数据描述符中的一致,这里就不过多讲解了。
主要讲一下get 和 set 方法的使用

2.2.1 get()与set()的使用

var obj = {
    name: 'jam',
    age: 8,
    _address: '河北'
}

// 存取描述符的使用场景
// 1.隐藏某一个私有属性被希望直接被外界使用和赋值
// 2.如果我们希望解惑某一个属性它访问和设置值的过程时,也会使用存储属性描述符
Object.defineProperty(obj, 'address', {
    enumerable: true,
    configurable: true,
    get: function () {
        foo()
        return this._address
    },
    set: function (value) {
        bar()
        this._address = value
    }
})
function foo () {
    console.log("截获了一次address的值")
}

function bar () {
    console.log("设置了一次address的值")
}

上述示例代码控制台打印结果如下:
JavaScript object-oriented detailed analysis of property descriptors

【相关推荐:javascript视频教程web前端

The above is the detailed content of JavaScript object-oriented detailed analysis of property descriptors. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete