Home >Web Front-end >JS Tutorial >Javascript accessor attribute example analysis_javascript skills

Javascript accessor attribute example analysis_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:23:041265browse

This article analyzes the usage of Javascript accessor attributes with examples and shares them with you for your reference. The specific analysis is as follows:

This has a similar meaning to a constructor, but its function is different. It can associate two attributes and change one attribute by modifying the other.

Copy code The code is as follows:
var book = {
_year:2004,
edition: 1
};
Object.defineProperty(book, "year", {
Get: function() {
         return this._year;
},
set: function(newValue) {
If (newValue > 2004) {
This._year = newValue;
This.edition = newValue - 2004;
}
}
});
book.year = 2006;
console.log(book.edition);

As can be seen from the above example, when _year is modified, only year is changed in the output value, but through set, edition is also changed when year is modified.

I hope this article will be helpful to everyone’s JavaScript programming design.

Statement:
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