系列文章目录
前面我们学习了set和map相关的知识,这一期我们讲解对象相关的知识
1、属性的简洁表示法
ES6 允许在⼤括号⾥⾯,直接写⼊变量和函数,作为对象的属性和⽅法。这样的书写更加简洁
const foo = 'bar';
const baz = {foo};
baz // {foo: "bar"}
// 等同于
const baz = {foo: foo};
上⾯代码中,变量foo直接写在⼤括号⾥⾯。这时,属性名就是变量名, 属性值就是变量值。下⾯是
另⼀个例⼦。
function f(x, y) {
return {x, y};
}
// 等同于
function f(x, y) {
return {x: x, y: y};
}
f(1, 2) // Object {x: 1, y: 2}
除了属性简写,⽅法也可以简写。
const o = {
method() {
return "Hello!";
}
};
// 等同于
const o = {
method: function() {
return "Hello!";
}
};
下⾯是⼀个实际的例⼦。
let birth = '2000/01/01';
CommonJS模块输出⼀组变量,就⾮常合适使⽤简洁写法。
简洁写法在打印对象时也很有⽤
const Person = {
name: '张三',
//等同于birth: birth
birth,
// 等同于hello: function ()...
hello() { console.log('我的名字是', this.name); }
};
//这种写法⽤于函数的返回值,将会⾮常⽅便。
function getPoint() {
const x = 1;
const y = 10;
return {x, y};
}
getPoint()
// {x:1, y:10}
CommonJS模块输出⼀组变量,就⾮常合适使⽤简洁写法。
let ms = {};
function getItem (key) {
return key in ms ? ms[key] : null;
}
function setItem (key, value) {
ms[key] = value;
}
function clear () {
ms = {};
}
module.exports = { getItem, setItem, clear };
// 等同于
module.exports = {
getItem: getItem,
setItem: setItem,
clear: clear
};
简洁写法在打印对象时也很有⽤
let user = {
name: 'test'
};
let foo = {
bar: 'baz'
};
console.log(user, foo)
// {name: "test"} {bar: "baz"}
console.log({user, foo})
// {user: {name: "test"}, foo: {bar: "baz"}}
- 上⾯代码中,console.log直接输出user和foo两个对象时,就是两组键值对,可能会混淆。
- 把它们放在⼤括号⾥⾯输出,就变成了对象的简洁表示法,每组键值对前⾯会打印对象名,这样就 ⽐较清晰了。
总结
本文讲解了对象方面的知识,下一期我们开始讲解对象的新增方法。