linxiaoziruo
V2EX  ›  问与答

es 中关于 this 指针丢失的问题

  •  
  •   linxiaoziruo · Nov 6, 2018 · 2032 views
    This topic created in 2784 days ago, the information mentioned may be changed or developed.

    let a = { name: ‘ zaki ’, say: function(param) { console.log(param); console.log(this); console.log(this.name); return param; } };

    (function() { a.say(); //可以打印出符合期望的的 this 信息 let fn = a.say; fn(1); // 不能打印出符合期望的 this 信息 })()

    4 replies    2018-11-07 17:09:05 +08:00
    ookkxw
        1
    ookkxw  
       Nov 6, 2018 via iPhone
    看你不知道的 js 基础问题,
    Tapir
        2
    Tapir  
       Nov 6, 2018   ❤️ 1
    基础知识
    call apply bind 都能解决问题
    ES 顺序看
    12.3.4Function Calls
    12.3.4.2Runtime Semantics: EvaluateCall ( func, ref, arguments, tailPosition )
    7.3.12Call ( F, V [ , argumentsList ] )
    9.2.1[[Call]] ( thisArgument, argumentsList )
    9.2.1.2OrdinaryCallBindThis ( F, calleeContext, thisArgument )
    这几部分
    关键点
    If thisArgument is undefined or null, then
    Let globalEnv be calleeRealm.[[GlobalEnv]].
    Let globalEnvRec be globalEnv's EnvironmentRecord.
    Assert: globalEnvRec is a global Environment Record.
    Let thisValue be globalEnvRec.[[GlobalThisValue]].
    hanzichi
        3
    hanzichi  
       Nov 6, 2018   ❤️ 1
    linxiaoziruo
        4
    linxiaoziruo  
    OP
       Nov 7, 2018
    老哥们,弄清楚了。多谢各位
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2477 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 31ms · UTC 11:07 · PVG 19:07 · LAX 04:07 · JFK 07:07
    ♥ Do have faith in what you're doing.