发表于: 2017-06-21 23:42:44
1 906
今天完成的事情:
学习了箭头函数:
箭头函数能使函数更容易的工作,比如
items.forEach(function(x) { //替换成items.forEach((x) => {
console.log(x);
incrementedItems.push(x+1);
});
计算一个表达式并返回值的函数可以被定义更简单:
incrementedItems = items.map((x) => x+1);
等于
incrementedItems = items.map(function (x) {
return x+1;
});
但是箭头函数和一般函数有一个很重要的区别: 箭头函数不会产生自己作用域下的 this, arguments, super和new.target等对象。当this 在一个箭头函数内部使用时候,JavaScript 会使用函数所在上下文的 this 值。
class Toppings {
constructor(toppings) {
this.toppings = Array.isArray(toppings) ? toppings : [];
}
outputList() {
this.toppings
.forEach((topping, i) => console
.log(topping, i + '/' + this.toppings.length) // `this` works!
)
}
}
var ctrl = new Toppings(['cheese', 'lettuce']);
this 指向的是实例变量
关于匿名函数或在其他函数中声明的函数
class ServerRequest {
notify() {
...
}
fetch() {
getFromServer(function callback(err, data) {
this.notify(); // 这不会生效
});
}
}
上面的this不会指向期望的对象:“strict”模式下,它将是未定义的。
明天计划的事情:
继续学习angular
注意的问题:
箭头函数没有 arguments 对象
收获:
箭头函数的使用
评论