前端新手,最近在补 JS 基础,参考了阮老师的《 ES6 入门》、MDN 上关于 this 的解释,还有这篇文章
目前关于箭头函数中 this 的理解,自己总结了如下三点:
-
箭头函数没有自己的 this,它指向函数定义时,外层普通函数的 this
-
外层普通函数的 this,可能会在函数调用时发生改变,进而导致箭头函数 this 的变化
-
因为箭头函数没有自己的 this,所以对其本身使用 call()、apply()、bind()方法都会失效
想请教各位,小弟上面的理解,是否还存在偏差?
另外,这篇文章中,如下代码:
var name = 'window'
function Person (name) {
this.name = name
this.show1 = function () {
console.log(this.name)
}
this.show2 = () => console.log(this.name)
this.show3 = function () {
return function () {
console.log(this.name)
}
}
this.show4 = function () {
return () => console.log(this.name)
}
}
var personA = new Person('personA')
var personB = new Person('personB')
personA.show1() // personA
personA.show1.call(personB) // personB
personA.show2() // personA
personA.show2.call(personB)// personA
personA.show3()() // window
personA.show3().call(personB) // personB
personA.show3.call(personB)() // window
personA.show4()() // personA
personA.show4().call(personB) // personA
personA.show4.call(personB)() // personB
作者关于
personA.show2.call(personB)// personA
的解释是
"因为构造函数闭包的关系,指向了构造函数作用域内的 this"
我是否可以用上面总结的第 3 点(因为箭头函数没有自己的 this,所以对其本身使用 call()、apply()、bind()方法都会失效)来解释?是否有问题?
感谢