js对象可扩展性和属性的四个特性(下)

时间:2019-12-08 15:52:54   收藏:0   阅读:80

# js对象可扩展性和属性的四个特性(下)

一、前言


二、目录

  • 对象属性的四个特性
  • 对象的可扩展性
  • 删除属性
  • 检测属性
  • 枚举属性
  • 属性的getter和setter

三、删除属性

1、用指定对象作为原型创建对象

Object.create()

说明:

    const log = console.log;
    //返回数据数据的描述
    var aa = Object.create({ x: 1 }, {
        y: {
            value: 1,
            writable: false,
            enumerable: false,
            configurable: true
        }

    })
    log(aa)
    log(Object.getOwnPropertyDescriptor(aa,'y'))

技术分享图片

2、删除对象属性

delete

说明:

    const log = console.log;
    //返回数据数据的描述
    var aa = {y:2}
    Object.defineProperty(aa, 'x', {
            value: 1,
            writable: true,
            enumerable: true,
            configurable: false
        })
    log(aa);
    log(delete aa.x);
    log(delete aa.y);
    log(aa)

技术分享图片


四、检测属性

1、检测对象是否拥有某个属性

in

说明:

    const log = console.log;
    var aa={x:1};
    log('x' in aa);
    log('y' in aa);
    log('toString' in aa)

技术分享图片

2、检测对象是否拥有某个属性

hasOwnProperty()

说明:

    const log = console.log;
    var aa={x:1};
    log(aa.hasOwnProperty('x'));
    log(aa.hasOwnProperty('y'));
    log(aa.hasOwnProperty('toString'))

技术分享图片

3、检测对象是否拥有某个属性

propertyIsEnumerable()

说明:

    const log = console.log;
    var aa = { x: 1 };
    Object.defineProperty(aa, 'y', {
        value: 1,
        writable: true,
        enumerable: false,
        configurable: true
    })
    log(aa)
    log(aa.propertyIsEnumerable('x'));
    log(aa.propertyIsEnumerable('y'));
    log(aa.propertyIsEnumerable('toString'))

技术分享图片


五、枚举属性

1、枚举对象中的属性

Object.keys()
    const log = console.log;
    var aa = { x: 1 ,y:2};
    Object.defineProperty(aa, 'z', {
        value: 3,
        writable: true,
        enumerable: false,
        configurable: true
    })
    log(aa)
    log(Object.keys(aa))

技术分享图片

2、枚举对象中的属性

Object.getOwnPropertyNames()
    const log = console.log;
    var aa = { x: 1 ,y:2};
    Object.defineProperty(aa, 'z', {
        value: 3,
        writable: true,
        enumerable: false,
        configurable: true
    })
    log(aa)
    log(Object.getOwnPropertyNames(aa))

技术分享图片


六、属性的getter和setter

说明:

    const log = console.log;
    var aa = { x: 1 ,
    get y(){
        return 1000;
    },
    set y(value){
        this.x+=value;
    }
    };
    log(aa)
    aa.y=1;
    log(aa)

技术分享图片

原文:https://www.cnblogs.com/Juaoie/p/12005768.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!