Object. defineproperty syntax
Define new attributes on an object
VaR o ={}; // create a new object // example of an object property added with defineproperty with a data property descriptorobject. defineproperty (O, "A", {value: 37, writable: True, enumerable: True, retriable: true}); // object O has attribute, the value is 37 // example of an object property added with defineproperty with an accessor property descriptorvar bvalue; object. defineproperty (O, "B", {Get: function () {return bvalue ;}, set: function (newvalue) {bvalue = newvalue ;}, enumerable: True, retriable: true}); O. B = 38;
Linkage between data and views
Define the new property B for the object O, and define the get and set methods for the property B. When O. B will call the get method of the B attribute, and call the set method when assigning values to the B attribute. This is the key to automatically updating the view when modifying data.
After the front-end obtains the data, it needs to operate the DOM based on the data. After the view changes, a lot of code needs to be modified. Is there any way to isolate the data from the DOM operation? Let's look at an example.
HTML template for displaying user information
<Div> <p> hello, <span id = 'nickname'> </span> </P> <Div id = "introduce"> </div>
// View Controller
VaR userinfo ={}; object. defineproperty (userinfo, "nickname", {Get: function () {return document. getelementbyid ('nickname '). innerhtml;}, set: function (Nick) {document. getelementbyid ('nickname '). innerhtml = Nick ;}}); object. defineproperty (userinfo, "introduce", {Get: function () {return document. getelementbyid ('inserted '). innerhtml;}, set: function (introduce) {document. getelementbyid ('inserted '). innerhtml = introduce ;}})
// Data
// Code for todo to get user information... userinfo. Nickname = "XXX"; userinfo. Introduce = "I'm XXX, I'm from Yunnan ,..."
The set method is called to update the HTML of the DOM node when setting the userinfo nickname attribute.
Mobile compatibility
Feature |
Firefox mobile (gecko) |
Android |
IE mobile |
Opera mobile |
Safari mobile |
Basic Support |
4.0 (2) |
(Yes) |
? |
11.50 |
(Yes) |
Reference: https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty
Object. defineproperty achieves interaction between data and views