Types of Properties--Accessor Properties

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. 


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值