javascript高级程序设计学习---对象的数据属性

原创 lianhaozhiyun 随笔 待整理 1094阅读 2014-08-20 16:05:33 举报

ECMAScript中有两种属性:数据属性和访问器属性
数据属性包含一个数据值的位置,在这个位置可以读取和写入值。
数据属性的特性包括:

设置了configurable为false之后不能再设置为true了,否则会报错;其他三个特性不会报错,能正确修改

要修改这四个特性,必须使用Object.defineProperty()【IE8不支持该方法】方法,传入的值是该特性所在的对象名,属性名(以字符串方式),特姓名,如:
示例一:
var wife = {
name:"hyn",
age:28,
birthday: new Date("1988-01-20"),

        printInfo:function(){
             alert(this.name + "," + this.age + "," + this.birthday);
        },

        setName:function(newName){
             this.name = newName;
        },

        showName:function(){
             alert(this.name);
        }
   }
   //弹出框显示“hyn”
   wife.showName();
   Object.defineProperty(wife,"name",{value:"hhh"});
   //弹出框显示“hhh”
   wife.showName();
   wife.setName("yyy");
   //弹出框显示“yyy”
   wife.showName();

示例二:
var wife = {
name:"hyn",
age:28,
birthday: new Date("1988-01-20"),

        printInfo:function(){
             alert(this.name + "," + this.age + "," + this.birthday);
        },

        setName:function(newName){
             this.name = newName;
        },

        showName:function(){
             alert(this.name);
        }
   }
   //弹出框显示“hyn”
   wife.showName();
   //设置了name的值为“hhh”,并且设置该属性不可修改
   Object.defineProperty(wife,"name",{writable:false,value:"hhh"});
  //弹出框显示“hhh”
   wife.showName();
  //由于设置了不可修改,下面这个语句修改失败
   wife.setName("yyy");
  //弹出框显示“hhh”
   wife.showName();

示例三:
var wife = {
name:"hyn",
age:28,
birthday: new Date("1988-01-20"),

        printInfo:function(){
             alert(this.name + "," + this.age + "," + this.birthday);
        },

        setName:function(newName){
             this.name = newName;
        },

        showName:function(){
             alert(this.name);
        }
   }
   wife.showName();
   delete wife.name;
  //执行到上句后的结果:
   wife.setName("yyy");
   //执行上一句后,wife对象中又有了name属性

javascript高级程序设计学习---对象的数据属性
//弹出框显示“yyy”
wife.showName();
//设置了wife的name属性不可配置,即不能被delete删除
Object.defineProperty(wife,"name",{configurable:false});
delete wife.name;
//执行了上一句后的结果,见图可知,wife的name属性没有delete没有成功:

javascript高级程序设计学习---对象的数据属性
wife.setName("nnn");
//设置wife的name属性为不可配置后,但不影响修改name的值
wife.showName()

示例四:
var wife = {
name:"hyn",
age:28,
birthday: new Date("1988-01-20"),

        printInfo:function(){
             alert(this.name + "," + this.age + "," + this.birthday);
        },

        setName:function(newName){
             this.name = newName;
        },

        showName:function(){
             alert(this.name);
        }
   }
   //弹出的提示框中有name
   for(value in wife)
   {
        alert(value);
   }
   //设置了wife的name的enumerable特性为false,使得name不能被for-in循环到
   Object.defineProperty(wife,"name",{enumerable:false});
   alert("=====================");
   //弹出的提示框中没有name
   for(value in wife)
   {
        alert(value);
   }
评论 ( 0 )
最新评论
暂无评论

赶紧努力消灭 0 回复