美文网首页
ES6-对象字面量的扩展

ES6-对象字面量的扩展

作者: 闪电西兰花 | 来源:发表于2018-06-28 00:26 被阅读0次
    //原始组合对象的写法
    <script type="text/javascript">
        const name = 'Asher';
        const age = 3;
        const birth = '2015-09';
    
        const user = {
            name: name,
            age: age,
            birth: birth
        }
        console.log(user);      //{name: "Asher", age: 3, birth: "2015-09"}
    </script>
    
    //属性名简写:当属性名和表示值的变量名一样时,只写一个就可以了
    <script type="text/javascript">
        const name = 'Asher';
        const age = 3;
        const birth = '2015-09';
    
        const user = {
            name,
            age,
            birth
        }
        console.log(user);      //{name: "Asher", age: 3, birth: "2015-09"}
    </script>
    
    //对象字面量方法的简写
    <script type="text/javascript">
        const name = 'Asher';
        const age = 3;
        const birth = '2015-09';
    
        const user = {
            name,
            age,
            birth,
            getName() {
                console.log(this.name);
            }
        }
        user.getName();       //Asher
    </script>
    
    //对象字面量的计算属性
    //组合对象时不用一个个添加属性
    <script type="text/javascript">
        const keys = ['name','age','birth'];
        const values = ['Asher',3,'2015-09'];
        const user = {
            [keys.shift()]: values.shift(),
            [keys.shift()]: values.shift(),
            [keys.shift()]: values.shift()
        }
        console.log(user);     //{name: "Asher", age: 3, birth: "2015-09"}
    </script>
    

    相关文章

      网友评论

          本文标题:ES6-对象字面量的扩展

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