代码之家  ›  专栏  ›  技术社区  ›  Deadpool

请解释为什么在下面的示例中输出是“未定义的”?[副本]

  •  -2
  • Deadpool  · 技术社区  · 7 年前

    <script>
    var foo = {
      bar: function() { return this.baz; },
      baz: 1
    };
    
    var a = (function(){
      return typeof arguments[0]();
    })(foo.bar);
    
    console.log(a);
    </script>

    注意:我已经通过了以下链接,但它并不能解释这一点 例子。这里没有构造函数。。。 How to access the correct `this` inside a callback?

    1 回复  |  直到 7 年前
        1
  •  1
  •   Mamun    7 年前

    arguments[0]() 正在执行 Window 上下文,但它没有在名称中定义任何对象属性 (属于 福 ). 这就是为什么你 undefined

    改变

    foo.bar
    

    到

    foo.bar.bind(foo)
    

    var foo = {
      bar: function() { return this.baz; },
      baz: 1
    };
    var a = (function(){
      console.log(this.constructor.name); // Window
      return typeof arguments[0]();
    })(foo.bar.bind(foo));
    
    console.log(a);