js属性类型

js中有两种属性:数据属性和访问属性
1、数据属性
configurable    enumberable     writeable    value  
调用Object.defineProperty()方法改变默认属性
实例:

var person ={};
Object.defineProperty(person,"name",{
writable: true,
value: "test"
});
alert(person.name);  //"test"
person.name= "change";
alert(person.name);  //"test"

PS:调用Object.defineProperty()改变一个属性时,如果不指定其余的属性,其默认值都变为为false;

2、访问器属性
configurable    enumberable    get   set
调用Object.defineProperty()方法改变默认属性  
实例:

var book = {
	oldYear : 2004 ,
	edition : 1
};
Object.defineProperty(book, "newYear",{
        get: function(){
		return this.oldYear;
	},
        set: function(newValue){
	    if(newValue > 2004) {
		this.oldYear = newValue;
		this.edition += newValue - 2004 ;
           }
	}
});
book.newYear = 2005;
alert(book.edition);  //2
PS:只指定getter将不能写, 只指定setter将不但能读

定义多个属性

var book = {};
Object.defineProperty(book, {
	oldYear:{
	   value:2004
	},
	edition:{
	    value:1
	},
	newYear:{
	    get: function(){
	    return this.oldYear;
	},
	set: function(newValue){
	    if(newValue > 2004) {
		this.oldYear = newValue;
		this.edition += newValue - 2004 ;
	}
     }
   }
});

你可能感兴趣的:(js属性类型)