首先要明白箭头函数的作用:
箭头函数除了让函数的书写变得很简洁,可读性很好外;最大的优点是解决了this执行环境所造成的一些问题。比如:解决了匿名函数this指向的问题(匿名函数的执行环境具有全局性),包括setTimeout和setInterval中使用this所造成的问题。
平时我们常见的window属性和方法有alter,document,parseInt,setTimeout,setInterval,localtion等等,这些在默认的情况下是省略了window前缀的。(window.alter = alter).
ES5:
全局环境下,this 始终指向全局对象(window), 无论是否严格模式;
console.log(this.document=== document); // true // 在浏览器中,全局对象为 window 对象: console.log(this === window); // true this.name = 'zhangsan'; console.log(window.name); // zhangsan
函数上下文调用
函数直接调用
普通函数内部的this分两种情况,严格模式和非严格模式。
非严格模式下,this 默认指向全局对象window
function f2(){ return this; } f2() === window; // true
而严格模式下, this为undefined
function f2(){ "use strict"; // 这里是严格模式 return this; } f2() === undefined; // true
ES6箭头函数的this:
由于箭头函数this是在定义函数时绑定的,不是在执行过程中绑定的,它会捕获其所在(即定义的位置)上下文的this值, 作为自己的this值,
- 所以 call() / apply() / bind() 方法对于箭头函数来说只是传入参数,对它的 this 毫无影响。
- 考虑到 this 是词法层面上的,严格模式中与 this 相关的规则都将被忽略。(可以忽略是否在严格模式下的影响)
一句话概括,es6箭头函数里的this
指的是定义这个函数时外层代码的this
,这句话可以从两个方面理解:
- es6箭头函数没有自己的
this
- es6箭头函数里的
this
是外层代码(定义时,非执行时)this
的引用
例如:
var Animal = function() { this.name = "Animal1"; // 下面那一行的this指向的是这外面的this this.speak = (name,words) => { console.log(this.name + ' is saying ' + words + '.'); } } var cat = new Animal(); cat.speak(22,"miao ~"); // Animal is saying miao ~. var speak = cat.speak; speak(33,"miao ~");