Trying to build a discord.js bot I ran into some mental gap.
Let’s say I need my console application
to be a puppy that does a trick and barks after that. So I would build a subclass for this in this fashion:
class MyPuppy extends Dog { constructor() { super({ name: 'Fido' }); } trick() { console.log(`- Gives paw -`); } }
But this wouldn’t make the application to bark. For that I assume the trick()
function would need to inherit some methods although I’m not an expert in Javascript.
My intuition tells me that I would need to declare the parent class
somewhat like this:
class Dog { constructor(props) { this.name = props.name; this.trick = () => { this.trick.prototype.bark = () => { console.log('Woof!') }; }; } }
But as this isn’t working and I don’t know what else is necessary to implement this behavior, this has stopped me to continue learning Node.js
. Would you have any advice on this application?
Advertisement
Answer
Have you tried invoking the bark
method from within the trick
method?
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()
Another way to look at this would be to add the default trick
behaviour inside the parent class and then execute the parent’s trick
method in all children’s trick
methods.
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()