【发布时间】:2019-11-13 14:05:24
【问题描述】:
当我运行下面的代码时,输出将是:
- 约翰(预期)
- 未定义(为什么???)
- 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