一句话概括,es6箭头函数里的this
指的是定义这个函数时外层代码的this
,这句话可以从两个方面理解:
- es6箭头函数没有自己的
this
- es6箭头函数里的
this
是外层代码(定义时,非执行时)this
的引用
我们用一个简单的例子理解一下
var Animal = function() {
this.name = "Animal";
this.speak = (words) => {
console.log(this.name + ' is saying ' + words + '.');
}
}
var cat = new Animal();
cat.speak("miao ~"); // Animal is saying miao ~.
var speak = cat.speak;
speak("miao ~"); // Animal is saying miao ~. In ES5, it should be undefined is saying miao~.
可以看到更改执行上下文,并没有影响到speak函数中的this指向。