Home > Web Front-end > JS Tutorial > Data attributes and memory attributes of JavaScript notes_javascript skills

Data attributes and memory attributes of JavaScript notes_javascript skills

WBOY
Release: 2016-05-16 15:07:08
Original
1492 people have browsed it

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

The difference between the two attributes

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

The method of setting data properties using Object.defineProperty() is as follows

var obj = {};
Object.defineProperty(obj, "prop", {
value: 1,
writable: true, //可写性
enumerable: true, //可枚举性
configurable: true //设置该属性是否能被删除,以及enumerable属性是否可以被修改
})
Copy after login

The method of setting memory properties using Object.defineProperty() is as follows

var obj = {};
Object.defineProperty(obj, "prop", {
get
set
enumerable: true, //可枚举性
configurable: true //设置该属性是否能被删除,以及enumerable属性是否可以被修改
})
Copy after login

From the above example, we observe that the memory attribute does not have the two attributes value and writable, but is replaced by the set and get attributes.

Memory Properties

After looking at the intuitive differences between data attributes and memory attributes, let’s take a detailed look at memory attributes, an attribute that is easily overlooked (this is me TT).

The biggest difference between memory attributes and data attributes is the addition of getters/setters, through which the value of the attribute can be operated and some practical functions can be implemented.

//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 '请输入一个大于n的值';
}
})
}
var obj = new serialnum();
obj.n = 2;
//2
obj.n = 0;
//Uncaught 请输入一个大于n的值
Copy after login

In the above example, the set function is used to control the value range of n.

The editor will introduce you to the js data attribute storage attribute here. I hope it will be helpful to you!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template