function
es6中function的写法变得无比简洁
function(i){return i +1 ;} //es5
(i) => i + 1;//es6
如果比较复杂,就加个{}把代码包起来
function(x, y) {
x++;
y--;
return x + y;
} //es5
(x,y) => {
x++;
y--;
return x + y;
} //es6
除开简洁,es6的function还有一个巨牛逼的功能,就是他解决了this的指向问题
class Animal {
constructor(){
this.type = 'animal'
}
says(say){
setTimeout(function(){
console.log(this.type + ' says ' + say)
}, 1000)
}
}
var animal = new Animal()
animal.says('hi') //undefined says hi
运行上面的代码会报错,这是因为setTimeout中的this指向的是全局对象。
所以为了让它能够正确的运行,传统的解决方法有两种:
第一种是将this传给self,再用self来指代this
第二种方法是用bind(this)
但如果我们改用箭头函数的形式去写就不用担心this的指向问题,这是因为当我们使用箭头函数时,函数体内的this对象,就是定义时所在的对象,而不是使用时所在的对象。
并不是因为箭头函数内部有绑定this的机制,实际原因是箭头函数根本没有自己的this,它的this是继承外面的,因此内部的this就是外层代码块的this。
default, rest
default就是默认值的意思,当一个应该传参的函数没有传参,可以指定一个默认值
function animal(type){
type = type || 'cat';
console.log(type);
}
animal() //传统写法
而我们用了es6
function animal(type = 'cat'){
console.log(type)
}
animal()
最后一个rest语法也很简单,直接看例子:
function animals(...types){
console.log(types)
}
animals('cat', 'dog', 'fish') //["cat", "dog", "fish"]