I was reading a book recently called You don’t know JavaScript, saw Object.defineProperty, and then thought about it carefully and realized that I only know that Vue uses this to do data hijacking, but I don’t know how it works, how many parameters, from this, to make a note

Use 1.

Without further ado, get right to the code

var myObject = 0;

0b ject.defineProperty(myObject,"a", {value: 2.writable: true.configurable: true.enumerable: true
    });
    
myObject.a;/ / 2
Copy the code

As shown in the figure, you receive three parameters, the first being the object to bind to, the second being the property of the object to bind to, if it doesn’t have the property, add the property, if it does, bind the property

Among them

var myObject = {};

0bject.defineProperty(myObject,"a", {value: 2.writable: false.// Unwritable!
    configurable: true.enumerable: true
    });
    
my0bject.a = 3;
myObject.a;/ / 2

Copy the code

Writable determines whether the value of a property can be modified. If false also changes the value in strict mode, an error is reported.

var myObject = {
    a:2
};

myObject.a = 3;
my0bject.a;  / / 3

0bject.defineProperty(myObject,"a", {value: 4.writable: true.configurable: false.// Not configurable!
    enumerable: true
    });
    
my0bject.a;/ / 4
my0bject.a = 5;
myObject.a;/ / 5
0bject.defineProperty (myObject,"a", {value: 6.writable: true.configurable: true.enumerable: true});// TypeError

Copy the code

Last defineProperty(..) A TypeError is generated, and attempts to modify a non-configurable property descriptor, whether in strict mode or not, will result in an error. Note: Changing the 64x to false disables the different control system, and it cannot be repealed.

Enumerable is an Enumerable property. If it is set to False, the for in loop will not loop over the property that is set to false. If it is true, it will loop over the property. I am also preparing for the interview recently. Cheer up for the interview, my good brothers