ES6 允许在大括号{}里面,直接写入变量和函数,作为对象的属性和方法,书写更加简洁
之前我们写一个对象是这样的
const person = {
name: 'yoyo',
age: 20,
address: function () {
return "上海市"
}
}
前面一篇讲到对象可以解构赋值,分别用变量接收对象的属性和方法
let {name, age, address} = person;
console.log(name); // yoyo
console.log(age); // 20
console.log(address()); // 上海市
那么反过来,我们定义的属性和方法,也可以变成一个对象
let name = 'yoyo';
let age = 20;
const address = function () {
return "上海市"
}
const person = {
name,
age,
address
}
console.log(person); // {name: 'yoyo', age: 20, address: ƒ}
或者在对象里面直接写函数
let name = 'yoyo';
let age = 20;
const person = {
name,
age,
address() {
return "上海市"
}
}
console.log(person); // {name: 'yoyo', age: 20, address: ƒ}
或者也可以用箭头函数
let name = 'yoyo';
let age = 20;
const person = {
name,
age,
address: () => '上海悠悠'
}
console.log(person); // {name: 'yoyo', age: 20, address: ƒ}
等价于
let name = 'yoyo';
let age = 20;
const person = {
name,
age,
address: function () {
return '上海悠悠'
}
}
console.log(person); // {name: 'yoyo', age: 20, address: ƒ}