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

时间:2019-11-13 14:05:24

标签: javascript this

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

  1. john(预期)
  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

五月

1 个答案:

答案 0 :(得分:3)

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