Javascript Object.defineProperty () method


Object.defineProperty Method can define a new property on an object, or modify the original property of the object and return the object.

The basic syntax format is as follows:

1 var data = {} // define an object
 2 Object.defineProperty(data,'name',{
 3     con figurable:false , // set whether the properties of the object can be modified / deleted (default is false)
 4     e numerable:false , // set whether the attribute of the object can be enumerated (false by default)
 five value:111 , // set the value of this property (value, object, function, etc.) to undefined by default
 six writable:false , // set whether the value of this property of the object can be modified (false by default)
 7 // get function, the return value of the function is used as the value of the property
 8 // set function, which is called when the attribute value is modified.
11       })

You can use this attribute to achieve bidirectional binding of Vue

1 var obj = {}
 2 Object.defineProperty(obj,'name',{
 3       set(val){
 4 $('#text'). Val (VAL); // sets or returns the value of the form field
 5 $('#textshow'). Text (VAL); // sets or returns the text content of the element
 6        },
 7       get(){}
 8 })
 9 $('#text').keyup(function(event){
10 =;
11 })
12 console.log(obj)

The effect is shown in the figure



When you set the value of a property in the console, the DOM page changes as well

The effect is shown in the figure



You can use the Object.defineProperties

The syntax format is:

 1 var obj = {};
 2 Object.defineProperties(obj, {
 3   'property1': {
 4     value: true,
 5     writable: true
 6   },
 7   'property2': {
 8     value: 'Hello',
 9     writable: false
10   }
11   // etc. etc.
12 });


OK, the first essay ends, ends, sprinkles flowers!

Recommended Today

Rust Study RoadMap

background In recent months, I began to learn rust, and began to write some code with rust. Now, I don’t have a deep understanding of rust, but it’s OK to write some code everyday, and I can learn the next step as needed. In the process of learning, the author also read a lot of […]