'this' returns 嵌套函数未定义

'this' returns undefined from a nested function

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

  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

5 月

您的 getName 函数没有 return 值。

  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()
  };