推荐关注
Meteor
JSLint - a JavaScript code quality tool
jsFiddle
D3.js
WebStorm
推荐书目
JavaScript 权威指南第 5 版
Closure: The Definitive Guide
Exceptionluo

求教 js 的问题

  •  
  •   Exceptionluo · Oct 14, 2017 · 3408 views
    This topic created in 3143 days ago, the information mentioned may be changed or developed.

    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 replies    2017-10-18 17:36:26 +08:00
    autoxbc
        1
    autoxbc  
       Oct 15, 2017
    你的运行环境有问题,我用浏览器和 node 运行,结果都是
    // oo.name o.name cc.name cc.name oo.name oofun2.name
    qiuyk
        2
    qiuyk  
       Oct 15, 2017
    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
       Oct 18, 2017
    @autoxbc 我多方测试应该不是运行环境的问题
    @qiuyk 我明白你的意思,我的困惑是箭头函数中的 this 到底该如何理解
    qiuyk
        4
    qiuyk  
       Oct 18, 2017
    @Exceptionluo 你可以这样理解,function 是会隐性传入 this,箭头函数不会。而 function 的 this 指向他的调用者,你可以调用 call 啊 bind 什么的改变 this 指向,而箭头函数的 this 就是声明的作用域里面 this,call/apply/bind 都忽略,和他调用者没有关系,所以对象方法不要乱用箭头函数
    Exceptionluo
        5
    Exceptionluo  
    OP
       Oct 18, 2017
    @qiuyk “ 箭头函数的 this 就是声明的作用域里面 this ” 这里的声明作用域可以理解为是箭头函数内部么? 箭头函数也是匿名函数? 返回的匿名函数在 window 下执行所以获取到的是全局属性? 对于箭头函数 call/apply/bind 都是无效的?
    可以这么理解么
    qiuyk
        6
    qiuyk  
       Oct 18, 2017
    @Exceptionluo 是指箭头函数声明时所处的作用域,以你这个为例,箭头函数就处在全局作用域了,this 就指向 window 了;是匿名函数;箭头函数在哪执行和结果没有关系;是的。
    Exceptionluo
        7
    Exceptionluo  
    OP
       Oct 18, 2017
    @qiuyk 这次真懂啦 Thanks♪(・ω・)ノ
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   891 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 32ms · UTC 20:21 · PVG 04:21 · LAX 13:21 · JFK 16:21
    ♥ Do have faith in what you're doing.