ECMA5中的新特性getter和setter

在以前版本的js中,获取一个对象的属性值得时候,其实访问的是他的数据属性的[[value]],写入的时候也是这个属性,但是有一点不好的地方就是我们在Java中有get和set两个方法可以对对象的某一个属性进行修改和读取,而且对于每一个属性只能有一个相对应得getter和setter方法与之对应,所以在js的ECMA5版本中重新定义了两个方法,我们可以在修改一个属性的时候调用这个setter方法做想做的事情。

var person = {
    _year: 2004,
    _edition: 1,
    get year () {
        return this._edition;
    },
    set year (newValue) {
        if (newValue > 2004) {
            this._edition += newValue - this._year;
            this._year = newValue;
        }
    }
};
person.year = 2009;
console.info(person._edition);//6
console.info(person._year);//2009
在上面的实例中我们的getter和setter方法的名称必须对应着一个属性,例如上面的是person.year,如果像触发上述的getter和setter方法,就必须把名称命名为year,否则不会调用,这也与java中的get和set方法一样。

当然也可以调用以前的老的方法来定义

var person = {
    _year: 2004,
    _edition: 1,
};
Object.defineProperty(person,'year',{
    get:function () {
        return this._edition;
    },
    set:function (newValue) {
        if (newValue > 2004) {
            this._edition += newValue - this._year;
            this._year = newValue;
        }
    }
});
person.year = 2010;
console.info(person._edition);//7
console.info(person._year);//2010
var person = {
    _year: 2004,
    _edition: 1,
};

person.__defineGetter__('year', function () {
    return this._edition;
});
person.__defineSetter__('year', function (newValue) {
    if (newValue > 2004) {
        this._edition += newValue - this._year;
        this._year = newValue;
    }
});

person.year = 2011;
console.info(person._edition);//8
console.info(person._year);//2011

同名方法函数,前缀set是设值方法函数,前缀get是取值方法,不要用function关键字

从例子可以看出,person本身的属性是_year而外部访问则是year,隐藏,安全。
另外,在js里以下划线开始的变量是private,即私有的

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值