对象字面量的增强
属性和方法的简洁表示法
// 1.对象字面量是什么// 实例化构造函数生成对象// const person = new Object();// person.age = 18;// person.speak = function () {};// 对象字面量// const person = {// age: 18,// speak: function () {}// };// 2.属性的简洁表示法// 键名和变量或常量名一样的时候,可以只写一个// const age = 18;// const person = {// // age: age// age// };// console.log(person);// 3.方法的简洁表示法// 方法可以省略冒号和 function 关键字const person = {// speak: function () {}speak() {}};console.log(person);
方括号语法
// 1.方括号语法的用法// const prop = 'age';// const person = {};// // person.prop = 18;// person[prop] = 18;// 方括号语法可以写在对象字面量中// const person = {// [prop]: 18// };// console.log(person);// 2.方括号中可以放什么// ${}// [值或通过计算可以得到值的(表达式)]// const prop = 'age';// const func = () => 'age2';// const person = {// // [prop]: 18// // [func()]: 18// // ['sex']: 'male'// ['s' + 'ex']: 'male'// };// console.log(person);// 3.方括号语法和点语法的区别// 点语法是方括号语法的特殊形式const person = {};// person.age 等价于 person['age']// 属性名由数字、字母、下划线以及 $ 构成,并且数字还不能打头的时候可以使用点语法// age18_$ √// 18age ×// 合法标识符可以用来作为变量或常量名// 当你的属性或方法名是合法标识符时,可以使用点语法,其他情况下请使用方括号语法
函数参数的默认值
函数参数的默认值是什么
// 1.认识函数参数的默认值// 调用函数的时候传参了,就用传递的参数;如果没传参,就用默认值// multiply(2, 1);// multiply(2);// 2.函数参数默认值的基本用法// const multiply = (x, y) => {// if (typeof y === 'undefined') {// y = 1;// }// return x * y;// };const multiply = (x, y = 1) => x * y;console.log(multiply(2));
函数参数默认值的注意事项
// 1.默认值的生效条件// 不传参数,或者明确的传递 undefined 作为参数,只有这两种情况下,默认值才会生效// const multiply = (x, y = 1) => x * y;// // console.log(multiply(2, 0));// // console.log(multiply(2, null));// console.log(multiply(2, undefined));// console.log(multiply(2));// 2.默认值表达式// 如果默认值是表达式,默认值表达式是惰性求值的// 3.设置默认值的小技巧// 函数参数的默认值,最好从参数列表的右边开始设置// const multiply = (x = 1, y) => x * y;// console.log(multiply(undefined, 2));const multiply = (x, y = 1) => x * y;console.log(multiply(2));
函数参数默认值的应用
// 1.接收很多参数的时候// const logUser = (username = 'ZhangSan', age = 0, sex = 'male') =>// console.log(username, age, sex);// logUser('Alex', 18, 'male');// logUser();// 2.接收一个对象作为参数// const logUser = options =>// console.log(options.username, options.age, options.sex);const logUser = ({ username = 'zhangsan', age = 0, sex = 'male' } = {}) =>console.log(username, age, sex);// logUser({// username: 'alex',// age: 18,// sex: 'male'// });// logUser({ username: 'alex' });// { username = 'zhangsan', age = 0, sex = 'male' } = { username: 'alex' }// logUser({});logUser();// { username = 'zhangsan', age = 0, sex = 'male' } = {}// { username = 'zhangsan', age = 0, sex = 'male' } = undefined
