Home > Article > Web Front-end > Understanding Proxy in es6 (with examples)
The content of this article is about the understanding of Proxy in es6 (with examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
Test question analysis: The understanding of proxy may extend to the two-way binding of vue
Proxy (proxy) definition
can be understood as The target object has a layer of interception, and external access to the object must pass through this layer of interception
Simple example:
const obj = new Proxy({}, { get: (target, key, receiver) => { return 'JS' console.log(`get ${key}`) }, set: (target, key, value, receiver) => { console.log(`set ${key}`) }, }) obj.name = 'JS 每日一题' // set name // JS 每日一题 obj.name // 这里进入get的回调函数,所有直接返回 JS
As can be seen from the above example, there is a mechanism for Proxy , you can rewrite external read and write operations
In addition to proxying get and set operations, proxy can also proxy other operations, as follows
handler.getPrototypeOf() // 在读取代理对象的原型时触发该操作,比如在执行 Object.getPrototypeOf(proxy) 时。 handler.setPrototypeOf() // 在设置代理对象的原型时触发该操作,比如在执行 Object.setPrototypeOf(proxy, null) 时。 handler.isExtensible() // 在判断一个代理对象是否是可扩展时触发该操作,比如在执行 Object.isExtensible(proxy) 时。 handler.preventExtensions() // 在让一个代理对象不可扩展时触发该操作,比如在执行 Object.preventExtensions(proxy) 时。 handler.getOwnPropertyDescriptor() // 在获取代理对象某个属性的属性描述时触发该操作,比如在执行 Object.getOwnPropertyDescriptor(proxy, "foo") 时。 handler.defineProperty() // 在定义代理对象某个属性时的属性描述时触发该操作,比如在执行 Object.defineProperty(proxy, "foo", {}) 时。 handler.has() // 在判断代理对象是否拥有某个属性时触发该操作,比如在执行 "foo" in proxy 时。 handler.get() // 在读取代理对象的某个属性时触发该操作,比如在执行 proxy.foo 时。 handler.set() // 在给代理对象的某个属性赋值时触发该操作,比如在执行 proxy.foo = 1 时。 handler.deleteProperty() // 在删除代理对象的某个属性时触发该操作,比如在执行 delete proxy.foo 时。 handler.ownKeys() // 在获取代理对象的所有属性键时触发该操作,比如在执行 Object.getOwnPropertyNames(proxy) 时。 handler.apply() // 在调用一个目标对象为函数的代理对象时触发该操作,比如在执行 proxy() 时。 handler.construct() // 在给一个目标对象为构造函数的代理对象构造实例时触发该操作,比如在执行new proxy() 时。
Intercept and monitor external access to objects
Reduce the complexity of functions or classes
Verify operations or manage required resources before complex operations
The above is the detailed content of Understanding Proxy in es6 (with examples). For more information, please follow other related articles on the PHP Chinese website!