'this'从嵌套函数返回未定义的值

问题描述 投票:-1回答:2

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

  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

五月

javascript this
2个回答
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()
  };

0
投票

你可以做

this.getName = () => this.name;
© www.soinside.com 2019 - 2024. All rights reserved.