Learn the usage of Reflect quickly

Reflect


foreword

Reflect is a built-in object that provides methods for intercepting JavaScript operations. These methods are the same as those of the proxy. Reflect is not a function object, so it is not constructible. New objects cannot be used.


why use

All properties and methods of Reflect are static (like the Math object) and you can use them directly.
Reflect is a new global object in ECMAScript 6, which provides a set of static methods to support the metaprogramming function of JavaScript.

It mainly has the following characteristics:

It has the same API as the Object object, and the names and parameters of the reflection methods are also the same as the corresponding Object methods. So you can use it easily.

The Reflect.get and Reflect.set methods are used instead of the native object access methods. For example:

Reflect.get(target, targetKey)
//获取对象身上某个属性的值,类似于 target[name]。
Reflect.set(target,  targetKey, value)
//设置对象属性,类似于target[name]=value或target.name=value

It is very simple to use.
In addition to these two commonly used property methods, there are also some definition objects. The following is an example of using the Reflect.defineProperty() method to define the properties of an object:

const obj = {
    
    };
Reflect.defineProperty(obj, 'name', {
    
    
  value: 'test',
  writable: false
});
console.log(obj.name); // test
obj.name = 'test1'; // TypeError: Cannot assign to read only property 'name' of object '

Because the object property is set to be read-only and cannot be written, it cannot be modified and an error will be reported.

Reflect.apply() apply is also what we call in js
For example:
I want to directly append the original array elements can do this

const array = ['a', 'b'];
const elements = [0, 1, 2];
array.push.apply(array, elements);
console.info(array); // ["a", "b", 0, 1, 2]

Of course you can also use Reflect.apply

function add(a, b) {
    
    
  return a + b;
}
const args = [2, 3];
console.log(Reflect.apply(add, null, args)); // 5

It is easy to understand that it is summation.

For more interesting examples, please refer to the official document MDN
link: MDN .

Summarize

Most of you have used it in vue3, and students who have seen the source code must have seen it, so let's use it quickly.

おすすめ

転載: blog.csdn.net/qq_43205326/article/details/130447923