ES5 defineProperty and ES6 proxy for data hijacking

mvvm data-driven, in fact, used data from hijacking the way to two-way data update

First to understand the data hijacking defineProperty
<!DOCTYPE html>
<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>
    
</body>
<script> 

The let myObj = {}; 
 Object.defineProperty (myObj, " name " , { 
     configurable: true , // . Configurable to that described if false, then the object may not modify the properties, can not delete the opposite true 
     / * Enumerable enumerable; 
     after to true four methods can be used to manipulate the properties 
     1. 
     for (I in the let myObj) { 
         the console.log (I); 
     } 
     2. 
     Object.keys (); 
     3. 
     the JSON.stringify 
     . 4. 
     Object.assign 
     * / 
     Enumerable: to true , 
    GET () { //When the time enters the acquired attribute get method, the operation can be modified to obtain a return value (must return a value) or acquired is undefined 
        // value built attribute acquisition object property value 
        return value; 
    }, 
    SET (newValue) { / / values of the parameter set newValue listener method set to be changed to obtain the value 
    // value of the object can be built-in attribute property changes 
    // value = "dd"; 
      value = newValue; 
    } 
}) 
myobj.name = " hum " ; 
the console.log (myobj.name); 

</ Script > 
</ HTML >
proxy data hijacking
<!DOCTYPE html>
<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>
    
</body>
<script> 

The let myObj = {};
 // the Proxy must instantiate a new object is returned 
// more convenient to use for each property not hijack 
the let obj   =  new new the Proxy (myObj, { 
    GET (target, Key) { // target represents the current the key is the object instance attribute name acquired 
     
        the console.log ( " GET .. " )
         return   target [key]; 
    }, 
    SET (target, key, value) { // target object representing the current instance key is the attribute name acquired value acquired attribute value of the current 
        target [Key] = value; 
    } 
}) 
obj.name =  " John Doe " ; 
the console.log (obj); 
</script>
</html>

 

Guess you like

Origin www.cnblogs.com/supermanGuo/p/11430378.html