您好,登錄后才能下訂單哦!
JavaScript訪問器(Getter和Setter),ECMAScript 5(2009)介紹了Getter和Setters。 Getters和setter允許您定義對象訪問器(Computed Properties)。
<!DOCTYPE html>
<html>
<meta charset="utf-8">
<title>js</title>
<body>
<h3>JavaScript Getters和Setters</h3>
<p> Getters和setter允許您通過方法獲取和設置屬性。</p>
<p>此示例使用lang屬性獲取語言屬性的值。</p>
<p id="demo"></p>
<script>
// 新建一個對象。
var person = {
firstName: "John",
lastName : "Doe",
language : "en",
get lang() {
return this.language;
}
};
// 使用getter顯示來自對象的數據:
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允許您通過方法獲取和設置屬性。</p>
<p>此示例使用lang屬性設置語言屬性的值。</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>完美的創建反對象:</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
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。