zoukankan      html  css  js  c++  java
  • 对象 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 (中国标准时间)
  • 相关阅读:
    java 编码问题
    关于时间
    页面
    关于微信
    01-jQuery的介绍
    15-BOM
    14-定时器
    13-JS中的面向对象
    12-关于DOM操作的相关案例
    购物车练习
  • 原文地址:https://www.cnblogs.com/mengfangui/p/9627865.html
Copyright © 2011-2022 走看看