es 中关于 this 指针丢失的问题

2018-11-06 14:41:40 +08:00
 linxiaoziruo

let a = { name: ‘ zaki ’, say: function(param) { console.log(param); console.log(this); console.log(this.name); return param; } };

(function() { a.say(); //可以打印出符合期望的的 this 信息 let fn = a.say; fn(1); // 不能打印出符合期望的 this 信息 })()

1328 次点击
所在节点    问与答
4 条回复
ookkxw
2018-11-06 14:51:12 +08:00
看你不知道的 js 基础问题,
Tapir
2018-11-06 18:01:30 +08:00
基础知识
call apply bind 都能解决问题
ES 顺序看
12.3.4Function Calls
12.3.4.2Runtime Semantics: EvaluateCall ( func, ref, arguments, tailPosition )
7.3.12Call ( F, V [ , argumentsList ] )
9.2.1[[Call]] ( thisArgument, argumentsList )
9.2.1.2OrdinaryCallBindThis ( F, calleeContext, thisArgument )
这几部分
关键点
If thisArgument is undefined or null, then
Let globalEnv be calleeRealm.[[GlobalEnv]].
Let globalEnvRec be globalEnv's EnvironmentRecord.
Assert: globalEnvRec is a global Environment Record.
Let thisValue be globalEnvRec.[[GlobalThisValue]].
hanzichi
2018-11-06 19:07:14 +08:00
linxiaoziruo
2018-11-07 17:09:05 +08:00
老哥们,弄清楚了。多谢各位

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

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

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

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

© 2021 V2EX