JavaScript notes data attributes and memory attributes _javascript tips

Source: Internet
Author: User

In JavaScript, the attributes of an object are divided into data properties and memory properties:

The difference between two types of attributes

We use Object.defineproperty () first to intuitively feel the difference between the two.

The method for setting data properties using Object.defineproperty () is as follows

var obj = {};
Object.defineproperty (obj, "prop", {
value:1,
writable:true,//writable
enumerable:true,/
/enumerable Configurable:true//Set whether the property can be deleted, and whether the enumerable property can be modified
})

Use Object.defineproperty () to set the storage properties as follows

var obj = {};
Object.defineproperty (obj, "prop", {
get
set
enumerable:true,//enumerable
Configurable:true// Set whether this property can be deleted, and whether the enumerable property can be modified
}

From the above example, we observed that the memory properties did not have the value and writable two attributes, and instead set and get properties.

Memory properties

After reading the visual differences between the data attributes and the memory properties, let's look at the properties of the memory properties that are easily overlooked (that is, I TT).

The biggest difference between the memory attribute and the data attribute is the addition of getter/setter, which can manipulate the value of the property and realize some practical functions.

example1
function Serialnum () {
var n =1; 
var prop = null;
Object.defineproperty (This, "n", {
get:function () {return
n;
},
set:function (value) {
if (value > N) n = value;
else throw ' Please enter a value greater than n ';
}}} var obj = new Serialnum ();
OBJ.N = 2;
2
OBJ.N = 0;
Uncaught Please enter a value greater than n

In the example above, the SET function is used to control the value range of N.

About JS data attribute storage Properties Small series on the introduction here, I hope to help you!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.