求教 js 的问题

2017-10-14 23:58:36 +08:00
 Exceptionluo

var name = "window.name"; var o = { name:'o.name', fn:function () { return this.oo.oofun() }, fnn:()=>{ return this.name }, oo:{ name:'oo.name', oofun:()=>{ return this.name }, oofun2:()=>{ this.name='oofun2.name'; return this.name } } };

var cc = {name:'cc.name'};

console.log( o.fn(), o.fnn(), o.fnn.apply(cc), o.fnn.bind(cc)(), o.oo.oofun(), o.oo.oofun2() );

//window.name window.name window.name window.name window.name oofun2.name 为什么结果这这样的呢

2612 次点击
所在节点    JavaScript
7 条回复
autoxbc
2017-10-15 05:10:19 +08:00
你的运行环境有问题,我用浏览器和 node 运行,结果都是
// oo.name o.name cc.name cc.name oo.name oofun2.name
qiuyk
2017-10-15 13:18:03 +08:00
var name = "window.name"; var o = { name:'o.name', fn:function () { return this.oo.oofun() }, fnn:function () { return this.name }, oo:{ name:'oo.name', oofun:function(){ return this.name }, oofun2:function(){ this.name='oofun2.name'; return this.name } } };

var cc = {name:'cc.name'};

console.log( o.fn(), o.fnn(), o.fnn.apply(cc), o.fnn.bind(cc)(), o.oo.oofun(), o.oo.oofun2() );
Exceptionluo
2017-10-18 09:09:35 +08:00
@autoxbc 我多方测试应该不是运行环境的问题
@qiuyk 我明白你的意思,我的困惑是箭头函数中的 this 到底该如何理解
qiuyk
2017-10-18 09:52:34 +08:00
@Exceptionluo 你可以这样理解,function 是会隐性传入 this,箭头函数不会。而 function 的 this 指向他的调用者,你可以调用 call 啊 bind 什么的改变 this 指向,而箭头函数的 this 就是声明的作用域里面 this,call/apply/bind 都忽略,和他调用者没有关系,所以对象方法不要乱用箭头函数
Exceptionluo
2017-10-18 13:01:12 +08:00
@qiuyk “ 箭头函数的 this 就是声明的作用域里面 this ” 这里的声明作用域可以理解为是箭头函数内部么? 箭头函数也是匿名函数? 返回的匿名函数在 window 下执行所以获取到的是全局属性? 对于箭头函数 call/apply/bind 都是无效的?
可以这么理解么
qiuyk
2017-10-18 17:04:14 +08:00
@Exceptionluo 是指箭头函数声明时所处的作用域,以你这个为例,箭头函数就处在全局作用域了,this 就指向 window 了;是匿名函数;箭头函数在哪执行和结果没有关系;是的。
Exceptionluo
2017-10-18 17:36:26 +08:00
@qiuyk 这次真懂啦 Thanks♪(・ω・)ノ

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

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

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

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

© 2021 V2EX