一、可计算属性

  1. 在引入可计算属性之前,如果想使用变量的值作为属性,那么必须先声明对象,然后使用中括号语法来添加属性,换句话说,不能在对象字面量中直接动态命名属性,比如:
  1. const nameKey = "name";
  2. const ageKey = "age";
  3. const jobKey = "job";
  4. let person = {};
  5. person[nameKey] = "Matt";
  6. person[ageKey] = 27;
  7. person[jobKey] = "Software engineer"
  1. 有了可计算属性,就可以在对象字面量中完成动态属性的赋值,中括号包围的对象属性键告诉运行时将其作为Javascript表达式而不是字符串来求值:
  1. const nameKey = "name";
  2. const ageKey = "age";
  3. const jobKey = "job";
  4. let person = {
  5. [nameKey]: "Matt",
  6. [ageKey]: 27,
  7. [jobKey]: "Software engineer"
  8. }
  9. console.log(person);
  10. // { name: 'Matt', age: 27, job: 'Software engineer' }
  1. 因为被当作JavaScript表达式求值,所以可计算属性本身可以是复杂的表达式,在实例化时再求值:
  1. const nameKey = "name";
  2. const ageKey = "age";
  3. const jobKey = "job";
  4. let uniqueToken = 0;
  5. function getUniqueKey(key) {
  6. return `${key}_${uniqueToken++}`;
  7. }
  8. let person = {
  9. [getUniqueKey(nameKey)]: "Matt",
  10. [getUniqueKey(ageKey)]: 27,
  11. [getUniqueKey(jobKey)]: "Software engineer"
  12. }
  13. console.log(person);
  14. // { name_0: 'Matt', age_1: 27, job_2: 'Software engineer' }

二、简写对象方法名

  1. 在给对象定义方法时,通常都要写一个方法名、冒号,然后再引用一个匿名函数表达式,如下所示:
  1. let person = {
  2. sayName: function(name) {
  3. console.log(`My name is ${name}`);
  4. }
  5. };
  6. person.sayName('Matt'); // My name is Matt
  1. 以下代码和之前的代码在行为上是等价的:
  1. let person = {
  2. sayName(name) {
  3. console.log(`My name is ${name}`);
  4. }
  5. };
  6. person.sayName('Matt'); // My name is Matt