【问题标题】:'this' returns undefined from a nested function'this' 从嵌套函数返回未定义
【发布时间】:2019-11-13 14:05:24
【问题描述】:

当我运行下面的代码时,输​​出将是:

  1. 约翰(预期)
  2. 未定义(为什么???)
  3. 25(预计)
function Person(name, age) {
  this.name = name;
  this.age = age;
  this.getName = function() {
    const self = this;
    function run() {
      console.log(self.name); // output "john"
      return self.name;
    }
    run();
  };
  this.getAge = function() {
    return this.age;
  };
}

const john = new Person("john", 25); 
console.log(john.getName()); // output undefined
console.log(john.getAge()); // output 25

五月

【问题讨论】:

  • const self = this; 移动到Person 函数。 this 不是你想的那样。
  • 因为你没有returnrun()的输出。

标签: javascript this


【解决方案1】:

您的getName 函数没有返回值。

  this.getName = function() {
    const self = this;
    function run() {
      console.log(self.name); // output "john"
      return self.name;
    }
    return run(); // <- You need to return the value of run()
  };

【讨论】:

  • 啊...我不敢相信我错过了。谢谢!
猜你喜欢
  • 1970-01-01
  • 2015-08-18
  • 1970-01-01
  • 2021-01-23
  • 1970-01-01
  • 2012-05-21
  • 1970-01-01
  • 2012-01-15
  • 2015-01-06
相关资源
最近更新 更多