preface
This is my second article on getting started.
The Proxy object in JS is a new way of intercepting, monitoring and operating objects proposed in ES2015. Through this object, the operation of objects can be intercepted and some custom processing can be carried out on the intercepted objects. Generally speaking, Proxy is like the guard of the company. The guard of the company will check and record anyone who enters the company. According to rules and regulations, it will reject those who are forbidden to enter and allow those who are allowed to enter and exit. The same is true for a Proxy, which performs different processing on a SINGLE JS object depending on the custom processing method we create.
The use of Proxy
const p = new Proxy(target, handler)
Target represents the object to be intercepted by Proxy. It can intercept not only general objects, but even arrays. Handler is an Object whose properties correspond to methods on the Object class, such as:
const handler = {
// This method is called when the listening Object calls Object.getProtoTypeof ()
getPrototypeOf(){... }}Copy the code
The most important methods are get and set. One is called when an object is accessed, and the other is used when an attribute of the object is assigned a value
const handler = {
get(target,name,property){
console.log('hello! '); // Every time an object is read, hello! Is printed on the console.
return Reflect.get(target,name,property); // Return the obtained value
},
set(target,name,value,property){
console.log('world! '); // World! Is printed on the console every time the object's value is changed.
return Reflect.set(target,name,value,property); }}let obj = {a:1}
const pro = new Proxy(obj,handler);
pro.a // Prints out 'hello' and 1
pro.a = 2; // Print 'world'
Copy the code
With this feature, we can implement a simple bidirectional binding.
Implement a simple bidirectional binding
<! DOCTYPEhtml>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="Width = device - width, initial - scale = 1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<input id="input" type="text" oninput="inputChange()"/>
</br>
<div id="show_value"></div>
<script>
let input = document.getElementById("input");
const showValue = document.getElementById("show_value");
const handler = {
set(target,name,value){
showValue.innerHTML = ` value is:${value}`;// When the SPY is notified, update the view
return Reflect.set(target,name,value); }}let spy = new Proxy(input,handler);
const inputChange = () = >{
spy.value = input.value; // Listen for the onInput method and notify the Proxy object SPY when input changes
}
</script>
</body>
</html>
Copy the code
Vue has better performance than Object.defineProperty after Proxy objects appear. Vue selected Proxy to listen on the object!