繁体   English   中英

如何设置/获取扩展 class 的属性?

[英]How to set / get a property of a extended class?

我有一个模板 class:

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 Personconstructor(info)info应该是 object。

我试过的:

var Person = require('./Person')
class Me extends Person{
     constructor(info) {
          super(info);
          this.name = 'Name'; //still does "undefined?"
     }
}

我什至尝试更改我的Person class。

class Person {
    constructor(name) {
        this.name = name;
    }
    talk() {
        return `${this.name} talked.`;
    }

}
module.exports = Person;

仍然返回undefined as this.name

如何从class Me中获取 class 属性,例如nameage ,以便他们返回诸如name = Meage = 18之类的内容?

老实说,尚不清楚属性应该“获取或设置”的确切位置 - 在Me class 或使用其实例时。

请检查此代码段是否适合您。

 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());

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM