学习新对象字面量语法

448 阅读1分钟

目标

  • 使用简写属性名称
  • 使用简写方法名称
  • 使用计算属性名称

问题

哪些部分是冗余的?

    const person={
        name:name,
        address:address,
        sayHello:function(){/*......*/},
        sayName:function(){/*......*/}
        sayAddress:function(){/*......*/}
    }

简写属性名称

//ES5
const message={text:text} //将属性text赋给text变量

//ES6
const message={ text }  //将属性text分配给名为text的变量

与解构结合使用

let {count} = stateManger.getState();  // 从转态管理器中检索出count
count+=amount;
stateManger.update({count})  //设置状态管理器中的count 

// 实际是{count:count} 第一行取出和第三行设置,这种对称性很优雅

简写方法名称

简写方法会被视为匿名函数,而不是命名函数,这意味着不能通过函数内部的名称来引用函数

 const fn={
    foo(n){
        if(n<=2) return 1;
        return foo(n-1) + foo(n-2)
    }
 }
 fn.foo(7)  //报错,foo未定义

只有在函数自引用的情况下,才会有关系,函数就像递归一样引用了自己

const person={
    sayHello:function sayHello(){
        console.log(123);
    }
}
person.sayHello(); //123

使用this解决这个问题

//this.foo在函数的上下文中调用,如果被独立开,就没用了
const fn={
    foo(n){
        if(n<=2) return 1;
        return this.foo(n-1) + this.foo(n-2)
    }
}
const {foo}=fn;
console.log(fn.foo(7));   //13
const fn2={foo};
console.log(fn2.foo(7));  //13
const fn3={f:foo};
console.log(fn3.f(7)); //this.foo is not a function

函数使用自我引用时,请不要使用简写方法名称

计算属性名称

计算属性允许在对象字面量上使用动态属性名称

const property='color';
const flower={
    [property]:'red'
}
console.log(flower.property); //undefined
console.log(flower.color); //red
console.log(flower.color); //red