Types of Properties--Accessor Properties

来源:互联网 发布:阿里云域名解析到主机 编辑:程序博客网 时间:2024/06/03 12:32

Accessor properties do not contain a data value.Instead ,they contain a combination of a getter function and a setter function(thought both are not necessary).When an accessor property is read from,the getter function is called ,and it's the function's responsibility to return a valid value;when an accessor  property is written to ,a function is called with the new value,and that function must decide how to react to the data.Accessor properties have four attributes:

[[Configurable]]--Indicates if the property may be redefined by removing the property via delete , changing the property's attributes,or changing  the property into a data property.By default ,this is true for all properties defined directly on an object.

[[Enumerable]]--Indicates if the property will be returned in a for-in loop.By default ,this is true for all properties defined directly on an object.

[[Get]]--The function to call when the property is  read from.The default value is undefined;

[[Set]]--The function to call when the property is written to.The default value is undefined.


It is not possible to define an accessor property explicitly ;you must use Object.defineProperty().Here is a simple example:

var book={

_year:2004,

edition:1

};

Object.defineProperty(book,'year',{

get:funtion(){

return this._year;

        },

set:function(newV){

if(newV>2004){

this._year=newV;

this.edition+=newV-2004;

}

}

}): 

book.year=2005;

alert(book.edition);//2

In this code,an object book is created with two default properties:_year and edition.The underscore on _year is a common notation to indicate that a property is not intended to be accessed from outside of the object's methods.The year property is defined to be an accessor property where the getter function simply return the value of _year and the setter does some calculation to determine the correct edition.So changing the year property to 2005 results in both _year and edition changing to 2.This is typical use case for accessor properties,when setting a property value results in some other changes to occur.


It's not necessary to assign both a getter and a setter.Assigning just a getter means that the property can not be written to and attempts to do so will be ignored . In strict mode,trying to write to a property with only a getter throws an error.Likewise, a property with only a setter can not be read an will return the value undefined in nonstrict mode, while doing so throws an error in strict mode. 


原创粉丝点击