您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
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进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。