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

关于 javascript 中 this 参数的问题

  •  
  •   jinxinking007 · 2018-07-23 17:48:54 +08:00 · 2730 次点击
    这是一个创建于 2075 天前的主题,其中的信息可能已经有所发展或是发生改变。

    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 条回复    2018-07-24 11:06:40 +08:00
    jinxinking007
        1
    jinxinking007  
    OP
       2018-07-23 17:52:19 +08:00
    这排版可读性太低,提取关键部分就是 getAge:function(){ return year=>year-this.birth; }和 getAge:()=>(y=>this.birth),两者的区别
    ysc3839
        2
    ysc3839  
       2018-07-23 17:57:46 +08:00 via Android
    guomuzz
        3
    guomuzz  
       2018-07-23 19:24:22 +08:00
    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  
       2018-07-24 09:17:55 +08:00
    箭头函数的 this 是在函数创建的时候就锁定了不能更改了的,就算用 call,apply,bind 也不行会报错
    zhzer
        5
    zhzer  
       2018-07-24 11:06:40 +08:00
    在 js 里的 json 对象,只是一层面向对象语法糖,相对来说不是特别严谨,箭头函数无法手动设定 this 也就无法适用这层修饰
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   4958 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 09:39 · PVG 17:39 · LAX 02:39 · JFK 05:39
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.