1.属性值简写
let name = "Jhon";
let person = {
name:name,
}
console.log(person);//{name: "Jhon"}
可以简写为:
let name = "Jhon";
let person={
name
}
console.log(person);//{name: "Jhon"}
2.可计算属性
const nameKey = 'name';
const ageKey = 'age';
let person = {};
person[nameKey] = "Matt";
person[ageKey] = "27";
console.log(person);//{name: "Matt", age: "27"}
const nameKey = 'name';
const ageKey = 'age';
let person = {
[nameKey] : "Matt",
[ageKey] : "27"
};
console.log(person);//{name: "Matt", age: "27"}
- 通过属性名包上中括号的方式,可以将变量值作为属性值,动态的为对象添加属性。
3.简写方法
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
方法名也可以用可计算属性键:
let functionKey = "sayName";
let person = {
[functionKey ](name){
console.log(`My name is ${name}`)
}
};
person.sayName('Matt');//My name is Matt