V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐关注
Meteor
JSLint - a JavaScript code quality tool
jsFiddle
D3.js
WebStorm
推荐书目
JavaScript 权威指南第 5 版
Closure: The Definitive Guide
Exceptionluo
V2EX  ›  JavaScript

求教 js 的问题

  •  
  •   Exceptionluo · 2017-10-14 23:58:36 +08:00 · 2571 次点击
    这是一个创建于 2357 天前的主题,其中的信息可能已经有所发展或是发生改变。

    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 为什么结果这这样的呢

    7 条回复    2017-10-18 17:36:26 +08:00
    autoxbc
        1
    autoxbc  
       2017-10-15 05:10:19 +08:00
    你的运行环境有问题,我用浏览器和 node 运行,结果都是
    // oo.name o.name cc.name cc.name oo.name oofun2.name
    qiuyk
        2
    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
        3
    Exceptionluo  
    OP
       2017-10-18 09:09:35 +08:00
    @autoxbc 我多方测试应该不是运行环境的问题
    @qiuyk 我明白你的意思,我的困惑是箭头函数中的 this 到底该如何理解
    qiuyk
        4
    qiuyk  
       2017-10-18 09:52:34 +08:00
    @Exceptionluo 你可以这样理解,function 是会隐性传入 this,箭头函数不会。而 function 的 this 指向他的调用者,你可以调用 call 啊 bind 什么的改变 this 指向,而箭头函数的 this 就是声明的作用域里面 this,call/apply/bind 都忽略,和他调用者没有关系,所以对象方法不要乱用箭头函数
    Exceptionluo
        5
    Exceptionluo  
    OP
       2017-10-18 13:01:12 +08:00
    @qiuyk “ 箭头函数的 this 就是声明的作用域里面 this ” 这里的声明作用域可以理解为是箭头函数内部么? 箭头函数也是匿名函数? 返回的匿名函数在 window 下执行所以获取到的是全局属性? 对于箭头函数 call/apply/bind 都是无效的?
    可以这么理解么
    qiuyk
        6
    qiuyk  
       2017-10-18 17:04:14 +08:00
    @Exceptionluo 是指箭头函数声明时所处的作用域,以你这个为例,箭头函数就处在全局作用域了,this 就指向 window 了;是匿名函数;箭头函数在哪执行和结果没有关系;是的。
    Exceptionluo
        7
    Exceptionluo  
    OP
       2017-10-18 17:36:26 +08:00
    @qiuyk 这次真懂啦 Thanks♪(・ω・)ノ
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   4123 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 05:24 · PVG 13:24 · LAX 22:24 · JFK 01:24
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.