美文网首页
JS - 对象(3)

JS - 对象(3)

作者: sunorry | 来源:发表于2015-02-01 16:35 被阅读27次

    get, set

    属性 getter/setter 方法

    var man = {
        name: 'sunorry',
        weibo: '@sunorry',
        get age() {
            return new Date().getFullYear() - 1990;
        },
        set age(val) {
            console.log('Age can\'t be set to ' + val);
        }
    };
    
    console.log(man.age); // 25
    man.age = 100; // Age can't be set to 100
    console.log(man.age); // still 25
    

    更复杂的例子
    var a = "abc";
    +a; // NaN

    var man = {
        weibo: '@sunorry',
        $age: null, //不想暴露给外部
        get age() {
            if(this.$age == undefined) {
                return new Date().getFullYear() - 1990;
            } else {
                return this.$age;
            }
        },
        set age(val) {
            val = +val; // 尝试转换成数字
            if(!isNaN(val) && val > 0 && val < 150) {
                this.$age = +val;
            } else {
                throw new Error('Incorrect val = ' + val);
            }
        }
    }
    
    console.log(man.age); // 27
    man.age = 100;
    console.log(man.age); // 100
    man.age = 'abc'; // error: Incorrect val = NaN
    

    get / set 与原型链

    function foo() {}
    
    Object.defineProperty(foo.prototype, 'z', {
        get: function() {
            return 1;
        }
    });
    
    var obj = new foo();
    
    obj.z; // 1
    obj.z = 10;
    obj.z; // still 1
    
    Object.defineProperty(obj, 'z', {
        value: 100,
        configurable: true
    });
    obj.z; // 100;
    delete obj.z;
    obj.z; // back to 1
    
    var o = {};
    Object.defineProperty(o, 'x', {
        value: 1
    }); // writeable=false, configurable=false
    var obj = Object.create(o);
    obj.x; // 1
    obj.x = 200;
    obj.x; // still 1, can't change it
    
    Object.defineProperty(obj, 'x', {
        writeable: true,
        configurable: true,
        value: 100
    });
    obj.x; // 100
    obj.x = 500;
    obj.x; // 500
    

    相关文章

      网友评论

          本文标题:JS - 对象(3)

          本文链接:https://www.haomeiwen.com/subject/aiglxttx.html