如何让子类中的方法函数继承一些属性

How can I make a method function inside a subclass inherit some properties

试图构建一个 discord.js 机器人,我 运行 陷入了某种精神空白。 假设我需要我的 console application 成为一只小狗,它会变戏法然后吠叫。所以我会以这种方式为此构建一个子类:

class MyPuppy extends Dog {

  constructor() {
    super({
      name: 'Fido'
    });
  }

  trick() {
    console.log(`- Gives paw -`);
  }

}

但是这不会让应用程序崩溃。为此,我假设 trick() 函数需要继承一些方法,尽管我不是 Javascript 方面的专家。 我的直觉告诉我,我需要像这样声明 parent class

class Dog {

  constructor(props) {
    this.name = props.name;
    this.trick = () => {
      this.trick.prototype.bark = () => {
        console.log('Woof!')
      };
    };
  }

}

但由于这不起作用,而且我不知道实现此行为还需要什么,这让我无法继续学习 Node.js。您对此申请有什么建议吗?

您是否尝试过从 trick 方法中调用 bark 方法?

class Dog {
    constructor(props) {
        this.name = props.name;
    }

    bark() {
        console.log("Woof!");
    }
}

class MyPuppy extends Dog {
    constructor() {
        super({
            name: 'Fido'
        });
    }

    trick() {
        console.log(`- Gives paw -`);
        this.bark();
    }
}

const puppy = new MyPuppy()
puppy.trick()

另一种看待这个问题的方法是在父 class 中添加默认的 trick 行为,然后在所有子 trick 中执行父的 trick 方法方法。

class Dog {
    constructor(props) {
        this.name = props.name;
    }

    bark() {
        console.log("Woof!");
    }

    trick() {
        this.bark();
    }
}

class MyPuppy extends Dog {
    constructor() {
        super({
            name: 'Fido'
        });
    }

    trick() {
        console.log(`- Gives paw -`);
        super.trick();
    }
}

new MyPuppy().trick()