您好,登錄后才能下訂單哦!
JavaScript訪問器(Getter和Setter),ECMAScript 5(2009)介紹了Getter和Setters。 Getters和setter允許您定義對(duì)象訪問器(Computed Properties)。
<!DOCTYPE html>
<html>
<meta charset="utf-8">
<title>js</title>
<body>
<h3>JavaScript Getters和Setters</h3>
<p> Getters和setter允許您通過方法獲取和設(shè)置屬性。</p>
<p>此示例使用lang屬性獲取語言屬性的值。</p>
<p id="demo"></p>
<script>
// 新建一個(gè)對(duì)象。
var person = {
firstName: "John",
lastName : "Doe",
language : "en",
get lang() {
return this.language;
}
};
// 使用getter顯示來自對(duì)象的數(shù)據(jù):
document.getElementById("demo").innerHTML = person.lang;
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<meta charset="utf-8">
<title>JavaScript Getters和Setters</title>
<body>
<h3> JavaScript Getters和Setters </h3>
<p> Getters和setter允許您通過方法獲取和設(shè)置屬性。</p>
<p>此示例使用lang屬性設(shè)置語言屬性的值。</p>
<p id="demo"></p>
<script>
// Create an object:
var person = {
firstName: "John",
lastName : "Doe",
language : "NO",
set lang(value) {
this.language = value;
}
};
// Set a property using set:
person.lang = "en";
// Display data from the object:
document.getElementById("demo").innerHTML = person.language;
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<meta charset="utf-8">
<title>js</title>
<body>
<h3> JavaScript Getters和Setters </h3>
<p>完美的創(chuàng)建反對(duì)象:</p>
<p id="demo"></p>
<script>
var obj = {
counter : 0,
get reset() {
this.counter = 0;
},
get increment() {
this.counter++;
},
get decrement() {
this.counter--;
},
set add(value) {
this.counter += value;
},
set subtract(value) {
this.counter -= value;
}
};
// Play with the counter:
obj.reset;
obj.add = 5;
obj.subtract = 1;
obj.increment;
obj.decrement;
// Display the counter:
document.getElementById("demo").innerHTML = obj.counter;
</script>
</body>
</html>
Object.defineProperty()方法還可用于添加Getters和Setter
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。