我试图通过方法访问构造函数中定义的名称,但它返回未定义。这是简单的代码:
class Person {
constructor(){
let name = 'Tom';
}
logName(){
console.log(this.name);
}
}
let x = new Person();
x.logName();
最佳答案
您需要将名称定义为对象的属性。在你的情况下 this.name
class Person {
constructor(){
this.name = 'Tom';
}
logName(){
console.log(this.name);
}
}
let x = new Person();
x.logName();
在您的代码中,您已在构造函数内定义了变量name
。它保留在那里,但没有逃脱。
关于javascript - 构造函数中定义的变量在类方法中不可用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50550921/