代码之家  ›  专栏  ›  技术社区  ›  Miguerurso

Javascript类继承无法正常工作

  •  1
  • Miguerurso  · 技术社区  · 3 年前

    尝试创建一些Javascript类和父类,但不确定是否正确,但子类中的super()没有正常工作。试图让DivElement中的内容正常工作,但它始终返回未定义的内容。

    代码:

     class HTMLElement{
        constructor(tag, content){
            this.tag = tag;
            this.content = content;
        }
    
        render(){
            return `<${this.tag}>${this.content}</${this.tag}>`;
        }
    
    class DivElement extends HTMLElement{
    constructor(content){
        super(content);
        this.tag = 'div';
       }
    
     }
    
    let div1 = new DivElement('test');
    console.log(div1);
    console.log(div1.render());
    
    2 回复  |  直到 3 年前
        1
  •  4
  •   Glycerine    3 年前

    超级调用应该与目标方法的签名匹配。应该是 super('div', content); :

    class HTMLElement{
        constructor(tag, content){
            this.tag = tag;
            this.content = content;
        }
    
        render(){
            return `<${this.tag}>${this.content}</${this.tag}>`;
        }
     }
    
    class DivElement extends HTMLElement{
        constructor(content){
        super('div', content);
        this.tag = 'div';
       }
    
     }
    
    let div1 = new DivElement('test');
    console.log(div1);
    console.log(div1.render());
    // <div>test</div>
    
        2
  •  0
  •   Lee Taylor Dejan.S    3 年前

    HtmleElement类的构造函数由两个参数(标记和内容)调用。扩展类只使用一个参数调用构造函数,并将内容分配给父类的标记参数。请注意,JS不允许构造函数重载。

    看看甘油的答案。