平时 js 写的不多,以下代码有个地方不太明白。
let func = () => ({ a: 1, b: () => { return this.a; } }); let instance = func(); console.log(instance.b()); // undefined
我记得如果this
在一个函数里面的话,this
会被设定为这个函数的调用者。在上面这段代码里调用b
的是instance
,所以this
应该就是instance
。显然instance.a === 1
是成立的,那为什么this.a
会返回undefined
?
1 FlowMEMO 2017-04-23 21:55:30 +08:00 箭头函数的 this 绑定和普通函数的不一样。 https://developer.mozilla.org/en-US/docs/Web/Javascript/Reference/Functions/Arrow_functions |
2 ZZZZZZZZTC 2017-04-23 21:57:43 +08:00 ()=>{} 貌似使用 this 会出错 |
![]() | 3 bdbai 2017-04-23 21:59:50 +08:00 via iPhone 箭头函数没有 this ,用到的是外层的 this 。这里最外层的 this 就是 undefined 。 你可以把箭头函数改成普通函数表达式再试试。 |
![]() | 4 aleen42 2017-04-23 22:10:30 +08:00 Arrow functions 会有一个 lexical this 的特性,因此函数中的 this 并非指向函数自身,而是外面一层,如 Window |
![]() | 5 aleen42 2017-04-23 22:12:53 +08:00 ![]() 所以你的代码在 ES5 等同: var self = this; function func() { return { a: 1, b: function () { return self.a; } }; } |
![]() | 6 SourceMan 2017-04-23 22:13:10 +08:00 via iPhone this 是外层的,不是 func 的,箭头函数导致的 你可以看看 babel 转换后的 |
![]() | 7 loy6491 2017-04-24 18:03:49 +08:00 ![]() 所以一般写成 b () { return this.a } |
8 TTPlayer 2017-04-25 14:09:21 +08:00 var func = function func() { return { a: 1, b: function b() { return undefined.a; } }; }; var instance = func(); console.log(instance.b()); // undefined 以上的 babel 转换成 es5 后的代码,可以参考一下 |
9 inickel 2017-04-27 15:56:54 +08:00 这里的 this 指向的是调用时的全局变量 |
![]() | 10 e8c47a0d 2017-10-09 10:27:05 +08:00 箭头函数里不能用 this |
![]() | 11 e8c47a0d 2017-10-09 10:30:02 +08:00 可以改成这样 let func = () => ({ a: 1, b() { return this.a } }) console.log(func().b()) |