What is the difference between creating an instance of object with new keyword and extending a class in JS?
First example with new keyword;
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a noise.`);
}
}
const dog = new Animal("Golden")
dog.bark = function(){console.log("bark")}
dog.bark()
Second example with extending:
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a noise.`);
}
}
class Dog extends Animal {
bark() {
console.log('Woof!');
}
}
const myDog = new Dog('Fido');
console.log(myDog.name); // expected output: "Fido"
myDog.bark(); // expected output: "Woof!"
Are these two doing the same thing? Which one should I use?