javascript面向对象之Object.defineProperty(a,b,c)

/*
Object.defineProperty(a,b,c);介绍
a:需要属性设置的对象
b:需要设置的属性名,(键值)
c:是一个用于描述属性值得json数据.这个json数据有configurable,eumerable,writable,value组成
configurable:1.能否被delete删除,2.他的属性值能否被修改.3.能否把属性设置成访问器属性,默认是true,可以删除,,修改,设置
eumerable:能否被for-in循环到
writable:表示属性值能否被修改
value:属性值.
*/

1  var human = {}
2     //将属性name设置成无法修改状态.
3     Object.defineProperty(human, "name", { writable: false, value: "晁天王" });
4     alert(human.name); //晁天王
5     human.name = "宋江";//严格模式下会报错 
6   alert(human.name); //宋江
1 //修改configurable为不可配置,则无法删除和修改属性的特性.
2     Object.defineProperty(human, "name", { configurable: false, value: "黑旋风李逵" });
3     alert(human.name); //黑旋风李逵
4     delete human.name;//严格模式下会报错 
5   alert(human.name); //黑旋风李逵
6   //一旦把配置属性configurable设置成false,就不能在设置成true了.否则会报错
7   Object.defineProperty(human, "name", { configurable: true, value: "天罡星玉麒麟卢俊义" });//下面是报错截图

访问器属性:

 1 var human = {
 2         _age:18,//下划线是一种常用的记号.用于只能通过对象方法访问的属性
 3         role:"大人"
 4     };
 5     Object.defineProperty(human, "age", {
 6         get: function () {//放回age属性值
 7             return this._age;
 8         },
 9         set: function (ageValue) {//设置对象中的属性值
10             if (ageValue >= 18)
11                 this.role = "大人";            
12             else
13                 this.role = "小孩";
14         }
15     });
16     human.age = 20;
17     alert(human.role); //大人
18     human.age = 10;
19     alert(human.role); //小孩

这个get和set在一起配合使用,可以很好的起到封装对象的作用.

原文地址:https://www.cnblogs.com/guoyansi19900907/p/3591411.html