
平时 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 年 4 月 23 日 箭头函数的 this 绑定和普通函数的不一样。 https://developer.mozilla.org/en-US/docs/Web/Javascript/Reference/Functions/Arrow_functions |
2 ZZZZZZZZTC 2017 年 4 月 23 日 ()=>{} 貌似使用 this 会出错 |
3 bdbai 2017 年 4 月 23 日 via iPhone 箭头函数没有 this ,用到的是外层的 this 。这里最外层的 this 就是 undefined 。 你可以把箭头函数改成普通函数表达式再试试。 |
4 aleen42 2017 年 4 月 23 日 Arrow functions 会有一个 lexical this 的特性,因此函数中的 this 并非指向函数自身,而是外面一层,如 Window |
5 aleen42 2017 年 4 月 23 日 所以你的代码在 ES5 等同: var self = this; function func() { return { a: 1, b: function () { return self.a; } }; } |
6 SourceMan 2017 年 4 月 23 日 via iPhone this 是外层的,不是 func 的,箭头函数导致的 你可以看看 babel 转换后的 |
7 loy6491 2017 年 4 月 24 日 所以一般写成 b () { return this.a } |
8 TTPlayer 2017 年 4 月 25 日 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 年 4 月 27 日 这里的 this 指向的是调用时的全局变量 |
10 e8c47a0d 2017 年 10 月 9 日 箭头函数里不能用 this |
11 e8c47a0d 2017 年 10 月 9 日 可以改成这样 let func = () => ({ a: 1, b() { return this.a } }) console.log(func().b()) |