我有一个模板类:
class Person {
constructor(info) {
this.name = info.name;
this.age = info.age;
}
talk() {
return `${this.name} talked.`;
}
}
module.exports = Person;
我还有另一个运行的文件:
var Person = require('./Person')
class Me extends Person{
constructor() {
super({
name: 'Me',
age: 18
})
}
}
如果我想再次检索,如何获取或设置名称?我的设置或设置正确吗?在class Person
、constructor(info)
、info
中,假定为对象。
我尝试过的:
var Person = require('./Person')
class Me extends Person{
constructor(info) {
super(info);
this.name = 'Name'; //still does "undefined?"
}
}
我甚至尝试更改我的Person
类。
class Person {
constructor(name) {
this.name = name;
}
talk() {
return `${this.name} talked.`;
}
}
module.exports = Person;
仍然返回undefined
作为this.name
如何从class Me
中获取name
或age
之类的类属性,以便它们返回name = Me
和age = 18
之类的内容?
老实说,属性应该在哪里还不清楚"获取或设置"-在CCD_ 12类中或使用其实例时。
请检查这个片段是否适合您。
class Person {
constructor(info) {
this.name = info.name;
this.age = info.age;
}
talk() {
return `${this.name} talked.`;
}
}
class Me extends Person{
constructor(info) {
super(info);
}
}
const me = new Me({ name: 'John', age: 19 });
console.log(me);
console.log(me.name);
console.log(me.age);
console.log(me.talk());
me.name = 'Jerry';
console.log(me);
console.log(me.name);
console.log(me.age);
console.log(me.talk());