阮一峰教程选取自己可能用到的特性
函数参数的默认值function log(x, y = 'World') {
console.log(x, y);
}
log('Hello') // Hello World
log('Hello', 'China') // Hello China
log('Hello', '') // Hello
与结构赋值默认值结合使用
foo()不带参数时不报错
function foo({x, y = 5} = {}) {
console.log(x, y);
}
foo() // undefined
rest参数
形如:...变量名,不需要使用arguments了,而且rest是一个真正的数组
// arguments变量的写法
function sortNumbers() {
return Array.prototype.slice.call(arguments).sort();
}
// rest参数的写法
const sortNumbers = (...numbers) => numbers.sort();
箭头函数注意点:this指向定义时的对象
不可以当做构造函数,不能使用new
不能用arguments对象,用rest代替
不可以用yield命令,不能用作Generator函数
const numbers = (...nums) => nums;
numbers(1, 2, 3, 4, 5)
// [1,2,3,4,5]
const headAndTail = (head, ...tail) => [head, tail];
headAndTail(1, 2, 3, 4, 5)
// [1,[2,3,4,5]]
双冒号运算符foo::bar;
// 等同于
bar.bind(foo);
foo::bar(...arguments);
// 等同于
bar.apply(foo, arguments);
const hasOwnProperty = Object.prototype.hasOwnProperty;
function hasOwn(obj, key) {
return obj::hasOwnProperty(key);
}