对象,get,set方法

1、用途

用户定义的对象定义 getter 和 setter 以支持新增的属性。

示例:obj创建一个伪属性latest,它会返回log数组的最后一个元素。

var obj = {
  log: ['example','test'],
  get latest() {
    if (this.log.length == 0) return undefined;
    return this.log[this.log.length - 1];
  }
}
console.log(obj.latest); // "test".

2、使用defineProperty在现有对象上定义 getter

var o = { a:0 }

Object.defineProperty(o, "b", { get: function () { return this.a + 1; } });

console.log(o.b) // Runs the getter, which yields a + 1 (which is 1

3、实用技巧

使用getter和setter方法扩展 Date原型,为预定义好的Date类添加一个year的属性。定义属性year的getter和setter方法用到了Date类中已存在的getFullYear和setFullYear方法。

Object.defineProperty(Date.prototype, "year", {
                get: function() {
                    return this.getFullYear()
                },
                set: function(y) {
                    this.setFullYear(y)
                }
            });
            var now = new Date();
            console.log(now.year); // 2018
            now.year = 2001;
            console.log(now); //Tue Sep 11 2001 15:10:43 GMT+0800 (中国标准时间)

猜你喜欢

转载自www.cnblogs.com/mengfangui/p/9627865.html