一、可计算属性
在引入可计算属性之前,如果想使用变量的值作为属性,那么必须先声明对象,然后使用中括号语法来添加属性,换句话说,不能在对象字面量中直接动态命名属性,比如:
const nameKey = "name";
const ageKey = "age";
const jobKey = "job";
let person = {};
person[nameKey] = "Matt";
person[ageKey] = 27;
person[jobKey] = "Software engineer"
有了可计算属性,就可以在对象字面量中完成动态属性的赋值,中括号包围的对象属性键告诉运行时将其作为Javascript表达式而不是字符串来求值:
const nameKey = "name";
const ageKey = "age";
const jobKey = "job";
let person = {
[nameKey]: "Matt",
[ageKey]: 27,
[jobKey]: "Software engineer"
}
console.log(person);
// { name: 'Matt', age: 27, job: 'Software engineer' }
因为被当作JavaScript表达式求值,所以可计算属性本身可以是复杂的表达式,在实例化时再求值:
const nameKey = "name";
const ageKey = "age";
const jobKey = "job";
let uniqueToken = 0;
function getUniqueKey(key) {
return `${key}_${uniqueToken++}`;
}
let person = {
[getUniqueKey(nameKey)]: "Matt",
[getUniqueKey(ageKey)]: 27,
[getUniqueKey(jobKey)]: "Software engineer"
}
console.log(person);
// { name_0: 'Matt', age_1: 27, job_2: 'Software engineer' }
二、简写对象方法名
在给对象定义方法时,通常都要写一个方法名、冒号,然后再引用一个匿名函数表达式,如下所示:
let person = {
sayName: function(name) {
console.log(`My name is ${name}`);
}
};
person.sayName('Matt'); // My name is Matt
以下代码和之前的代码在行为上是等价的:
let person = {
sayName(name) {
console.log(`My name is ${name}`);
}
};
person.sayName('Matt'); // My name is Matt