• 请不要在回答技术问题时复制粘贴 AI 生成的内容
ssshooter
V2EX  ›  程序员

这是浏览器的 bug 还是 feature,我的 this 呢?

  •  
  •   ssshooter ·
    ssshooter · Nov 15, 2021 · 3235 views
    This topic created in 1664 days ago, the information mentioned may be changed or developed.

    MJF5~FMPX_42@_S_IGGL_C3.png

    12 replies    2021-11-15 22:22:29 +08:00
    cxe2v
        1
    cxe2v  
       Nov 15, 2021
    箭头函数内的 this 有它自己的想法

    一般来说是继承上级词法作用域的 this ,这里看来是继承了 map 这个 function 的 this
    ssshooter
        2
    ssshooter  
    OP
       Nov 15, 2021
    qiguai2017
        3
    qiguai2017  
       Nov 15, 2021
    箭头函数没有 this 变量
    hgc81538
        5
    hgc81538  
       Nov 15, 2021
    var self = this;

    (function(){
    console.log(this, self);
    })()
    forgcode
        6
    forgcode  
       Nov 15, 2021
    为啥要用 eval 而不直接 this.valuesJson[question.variable]。箭头函数会被编译吧,编译之后是临时变量就是不 this 了,写在 eval 中的 this 不会被编译到
    codehz
        7
    codehz  
       Nov 15, 2021
    原因是被编译( ES6->ES5 )成
    var _this = this
    ... map(function (question) {
    eval('this.xxx' + xxx)
    });
    这样了。。。
    显而易见编译不可能处理 eval 里面的东西(
    kid740246048
        8
    kid740246048  
       Nov 15, 2021
    本质原因是 eval 的调用者是 window ,你开个 F12 跑下这行代码就知道了
    `eval("console.log(this)")`
    cheese
        9
    cheese  
       Nov 15, 2021
    原因楼上说了,但是我想知道这里为啥要 eval 啊?
    ssshooter
        10
    ssshooter  
    OP
       Nov 15, 2021
    @cheese 因为懒得写个 while ,variable 可能是 `a.b.c.d`
    ssshooter
        11
    ssshooter  
    OP
       Nov 15, 2021
    @forgcode
    @codehz 感谢
    cheese
        12
    cheese  
       Nov 15, 2021
    @ssshooter #10 对象的深层属性获取,可以看下 lodash 的_.get 还挺好用的 https://lodash.com/docs/#get
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2813 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 69ms · UTC 09:51 · PVG 17:51 · LAX 02:51 · JFK 05:51
    ♥ Do have faith in what you're doing.