对象的扩展

2020-06-15  本文已影响0人  向上而活

ES5给Object扩展了好一些静态方法, 常用的2个:

  1. Object.create(prototype, [descriptors])
  1. Object.defineProperties(object, descriptors)
<script type="text/javascript">
    var obj = {name : 'curry', age : 29}
    var obj1 = {};
    obj1 = Object.create(obj, {
        sex : {
            value : '男',
            writable : true
        }
    });
    obj1.sex = '女';
    console.log(obj1.sex);

    //Object.defineProperties(object, descriptors)
    var obj2 = {
        firstName : 'curry',
        lastName : 'stephen'
    };
    Object.defineProperties(obj2, {
        fullName : {
            get : function () {
                return this.firstName + '-' + this.lastName
            },
            set : function (data) {
                var names = data.split('-');
                this.firstName = names[0];
                this.lastName = names[1];
            }
        }
    });
    console.log(obj2.fullName);
    obj2.firstName = 'tim';
    obj2.lastName = 'duncan';
    console.log(obj2.fullName);
    obj2.fullName = 'kobe-bryant';
    console.log(obj2.fullName);
</script>

对象本身的两个方法
* get propertyName(){} 用来得到当前属性值的回调函数
* set propertyName(){} 用来监视当前属性值变化的回调函数

<script type='text/javascript'>
    var obj = {
        firstName : 'kobe',
        lastName : 'bryant',
        get fullName(){
            return this.firstName + ' ' + this.lastName
        },
        set fullName(data){
            var names = data.split(' ');
            this.firstName = names[0];
            this.lastName = names[1];
        }
    };
    console.log(obj.fullName);
    obj.fullName = 'curry stephen';
    console.log(obj.fullName);

</script>
上一篇下一篇

猜你喜欢

热点阅读