关于箭头函数中 this 的一点理解

2017-10-20 16:04:16 +08:00
 enginex

前端新手,最近在补 JS 基础,参考了阮老师的《 ES6 入门》MDN 上关于 this 的解释,还有这篇文章

目前关于箭头函数中 this 的理解,自己总结了如下三点:

  1. 箭头函数没有自己的 this,它指向函数定义时,外层普通函数的 this

  2. 外层普通函数的 this,可能会在函数调用时发生改变,进而导致箭头函数 this 的变化

  3. 因为箭头函数没有自己的 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()方法都会失效)来解释?是否有问题?

感谢

2688 次点击
所在节点    JavaScript
8 条回复
KuroNekoFan
2017-10-20 16:54:19 +08:00
我觉得解释应该是`call(personB)调用无效`
enginex
2017-10-20 17:10:11 +08:00
@KuroNekoFan 额,和用总结的第 3 点来解释,有什么差别吗?
binux
2017-10-20 17:24:20 +08:00
根本不需要第三点,你看看 babel 是怎么编译 arrow function 的就知道了。

function A() {
var _this = this;

this.a = function () {
_this.name;
};
}

_this 都写死了,你重新绑定有什么用?
enginex
2017-10-20 17:34:57 +08:00
@binux 嗯,我也是这么理解的,但怕哪天自己又忘了去瞎纠结,所以给自己又加了条
KuroNekoFan
2017-10-20 17:43:04 +08:00
@enginex https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions mdn 是这么解释的
Since arrow functions do not have their own this, the methods call() or apply() can only pass in parameters. thisArg is ignored.
469054193
2017-10-20 17:48:24 +08:00
箭头函数的 this 看作用域. 上层有 function 的话则 this 指向就是那个 function 的指向. 如果没有就是 window
xieguanglei
2017-10-20 17:57:48 +08:00
不错,理解得挺对的
enginex
2017-10-21 09:44:52 +08:00
@KuroNekoFan 感谢提醒,差点忘了还有传参

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/399279

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX