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

JS - 对象(4)

作者: sunorry | 来源:发表于2015-02-01 17:58 被阅读21次

    属性标签

    属性级的权限设置

    查看对象上的属性标签

    Object.getOwnPropertyDescriptor({
        pro: true
    }, 'pro');
    // 可写,修改; 可枚举; 可删除
    // Object {value: true, writable: true, enumerable: true, configurable: true}
    Object.getOwnPropertyDescriptor({
        pro: true
    }, 'a'); // undefined
    
    var person = {};
    Object.defineProperty(person, 'name', {
        configurable: false,
        writable: false,
        enumerable: true,
        value: 'sunorry'
    });
    
    person.name; // sunorry
    person.name = 1;
    person.name; //still sunorry
    delete person.name; //false
    
    Object.defineProperty(person, 'type', {
        configurable: true,
        writable: true,
        enumerable: false,
        value: 'Object'
    });
    
    // 返回对象的key
    Object.keys(person); // ['name'], type不可枚举
    

    实际一点的例子

    //默认 false
    Object.defineProperties(person, {
        title: {value: 'fe', enumerable: true},
        corp: {value: 'Qunar', enumerable: true},
        salary: {value: 1000, enumerable: true, writable: true}
    });
    
    Object.getOwnPropertyDescriptor(person, 'salary');
    // Object {value, 1000, writeable: true, enumerable: true, configurable: false}
    Object.getOwnPropertyDescriptor(person, 'corp');
    // Object {value, 'Qunar', writeable: false, enumerable: true, configurable: false}
    

    复杂点

    
    Object.defineProperties(person, {
        title: {value: 'fe', enumerable: true},
        corp: {value: 'Qunar', enumerable: true},
        salary: {value: 1000, enumerable: true, writable: true},
        luck: {
            get: function () {
                return Math.random() > 0.5 ? 'good' : 'bad';
            }
        },
        promote: {
            set: function(level) {
                this.salary *= 1 + level * 0.1
            }
        }
    });
    
    Object.getOwnPropertyDescriptor(person, 'salary');
    // Object {value, 1000, writeable: true, enumerable: true, configurable: false}
    Object.getOwnPropertyDescriptor(person, 'corp');
    // Object {value, 'Qunar', writeable: false, enumerable: true, configurable: false}
    
    person.salary; // 1000
    person.promote = 2;
    person.salary; // 1200
    
    Paste_Image.png

    相关文章

      网友评论

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

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