【问题标题】:Execution Context with "Console.log()" [duplicate]带有“Console.log()”的执行上下文 [重复]
【发布时间】:2021-05-20 20:16:51
【问题描述】:

据我所知,“执行上下文”是由调用函数的位置决定的,而不是声明函数的位置。

因此,在下面的示例中,我希望 this.name 评估为未定义。因此,我不确定console.log() 是如何访问“特许经营”对象内的this 关键字的。

let franchise = {
  name: 'How to Train Your Dragon',
  allMovies: function() {
    console.log(this.name)
  },
};

franchise.allMovies() // How to Train Your Dragon

我希望它评估为“未定义”的原因与此示例中的相同:

let franchise = {
  name: 'How to Train Your Dragon',
  allMovies: function() {
    function print() {
      return this.name;
    }
    return print(); //undefined
  }
};

【问题讨论】:

  • "所以在下面的示例中,我希望 this.name 的计算结果为 undefined。" 为什么?
  • 为问题添加了额外的上下文
  • 您的第二个代码返回undefined,因为print 的调用方式,而不是franchise.allMovoes() 的调用方式。根据经验,当您使用() 执行常规函数时,this 的值将变为最后一个. 之前的值,因此a.b.c() 使用this = a.b 执行.c()a.b() 执行 .b()this = aa() 执行 a()this = undefined(在草率模式下将替换为全局对象); franchise.allMovies()a.b() 形式,所以this = franchiseprint()a() 形式。

标签: javascript this executioncontext


【解决方案1】:

this.name 被评估(那个 Dragon 字符串)并作为参数传递给 console.log。控制台与this 无关 - 只是输出它的参数。

【讨论】:

    猜你喜欢
    • 2016-11-02
    • 2014-07-24
    • 1970-01-01
    • 2020-03-11
    • 2019-07-03
    • 2012-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多