理解Object.defineProperty()

Method Description:

It is used to define or modify the properties of an object.

A total of three parameters are necessary: ​​obj- audiences, newKey- attribute name, {} - attribute properties

Characteristic attributes are added to the object description (third parameter), it is available in two forms: Data description and accessors described.

 

Data Description:

Object.defineProperty (obj, "newKey", { 
  value: "the Hello", // set the value of the property 
  writable: false, // whether the value can be overridden .true | false 
  Enumerable: false, // whether the target attribute can be gold for .true | false (or use the for ... in Object.keys ()) 
  the Configurable: false // whether the target attribute can be deleted or whether it can be made again characteristic to true | false 
});

 

Accessor Description:
Note: When using a getter or setter method, and the value is not allowed to use these two attributes writable

Copy the code
obj = {} var; 
var initValue = 'Hello'; 
Object.defineProperty (obj, "newKey", { 
    GET: function () { 
        // Get the time when the function value of the trigger 
        return initValue;     
    }, 
    SET: function (value ) { 
        function // when the set value when triggered, to get the new value of the parameter value 
        initValue = value; 
    } 
}); 
// get the value of 
the console.log (obj.newKey); Hello // 

// set value 
= obj.newKey 'Change value'; 

the console.log (obj.newKey); // Change value
Copy the code

 

Guess you like

Origin www.cnblogs.com/shaozhu520/p/12604765.html