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

关于 javascript 中 this 参数的问题

  •  
  •   jinxinking007 · Jul 23, 2018 · 3549 views
    This topic created in 2858 days ago, the information mentioned may be changed or developed.

    var obj={ birth:1995, getAge:function(year){ var that=this; function getAge(){ return new Date().getFullYear()-that.birth; } return getAge(); } }; var obj3={ birth:1997, getAge:function(){ return year=>year-this.birth; } }; var obj2={ birth:1996, getAge:()=>(y=>this.birth), }; console.log(obj.getAge(2018)); console.log(obj3.getAge()(2018)); console.log(obj2.getAge()(2018));

    输出结果为: 23 21 undefined

    第一种使用了一种 hack 方法规避了 this 的 bug,二三两种用的都是箭头函数,为什么二可行,而三不可行呢?

    5 replies    2018-07-24 11:06:40 +08:00
    jinxinking007
        1
    jinxinking007  
    OP
       Jul 23, 2018
    这排版可读性太低,提取关键部分就是 getAge:function(){ return year=>year-this.birth; }和 getAge:()=>(y=>this.birth),两者的区别
    ysc3839
        2
    ysc3839  
       Jul 23, 2018 via Android
    guomuzz
        3
    guomuzz  
       Jul 23, 2018
    var obj3 = {
    birth: 1997,
    getAge: function () {
    console.log(this)
    return year => year - this.birth;
    }
    };
    var obj2 = {
    birth: 1996,
    getAge: () => {
    console.log(this)
    return y => this.birth
    },
    };

    打印一下就知道了
    DrugsZ
        4
    DrugsZ  
       Jul 24, 2018
    箭头函数的 this 是在函数创建的时候就锁定了不能更改了的,就算用 call,apply,bind 也不行会报错
    zhzer
        5
    zhzer  
       Jul 24, 2018
    在 js 里的 json 对象,只是一层面向对象语法糖,相对来说不是特别严谨,箭头函数无法手动设定 this 也就无法适用这层修饰
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5047 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 40ms · UTC 09:30 · PVG 17:30 · LAX 02:30 · JFK 05:30
    ♥ Do have faith in what you're doing.