=> 的作用:
1:将this与当前词法作用域绑定;
2:简化代码; 本来需要 self = this;现在只需要()=>{…} 就可以了;
**p => p.name的含义**:引用codewars的用户 AcesOfGlory的解释如下:
It's called an arrow function and it's part of the new ES6 JavaScript update. It maps the array and looks at every object item in it; for each of the objects (named p), it will return the name (the first item) instead of the whole object.
p => p.name
is the same as
names.map(function(){return p.name})
p = {name: 'Bart'}
p.name = 'Bart'
即它会遍历数组中的每一个字符,并会返回名为p的对象的name属性,而不是返回它的整个对象;
代码如下:
var obj = {
id: id,
cool:function Fn(){
setTimeout(()=>{
console.log(this.id},100);}
}
}
obj.cool()
如果没有绑定,就需要这样做:
var obj = {
id: id,
cool:function Fn(){
var self = this;
setTimeout(timer(){
console.log(self.id},100);}
}
}
obj.cool()