这是浏览器的 bug 还是 feature,我的 this 呢?

2021-11-15 18:09:59 +08:00
 ssshooter

2337 次点击
所在节点    程序员
12 条回复
cxe2v
2021-11-15 18:21:04 +08:00
箭头函数内的 this 有它自己的想法

一般来说是继承上级词法作用域的 this ,这里看来是继承了 map 这个 function 的 this
ssshooter
2021-11-15 18:28:44 +08:00
qiguai2017
2021-11-15 19:22:28 +08:00
箭头函数没有 this 变量
qiguai2017
2021-11-15 19:25:02 +08:00
hgc81538
2021-11-15 19:49:56 +08:00
var self = this;

(function(){
console.log(this, self);
})()
forgcode
2021-11-15 19:50:34 +08:00
为啥要用 eval 而不直接 this.valuesJson[question.variable]。箭头函数会被编译吧,编译之后是临时变量就是不 this 了,写在 eval 中的 this 不会被编译到
codehz
2021-11-15 20:22:32 +08:00
原因是被编译( ES6->ES5 )成
var _this = this
... map(function (question) {
eval('this.xxx' + xxx)
});
这样了。。。
显而易见编译不可能处理 eval 里面的东西(
kid740246048
2021-11-15 20:23:46 +08:00
本质原因是 eval 的调用者是 window ,你开个 F12 跑下这行代码就知道了
`eval("console.log(this)")`
cheese
2021-11-15 20:28:29 +08:00
原因楼上说了,但是我想知道这里为啥要 eval 啊?
ssshooter
2021-11-15 21:47:55 +08:00
@cheese 因为懒得写个 while ,variable 可能是 `a.b.c.d`
ssshooter
2021-11-15 21:48:30 +08:00
@forgcode
@codehz 感谢
cheese
2021-11-15 22:22:29 +08:00
@ssshooter #10 对象的深层属性获取,可以看下 lodash 的_.get 还挺好用的 https://lodash.com/docs/#get

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

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

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

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

© 2021 V2EX