class
keyword in javascript is just a syntactic sugar. Let' see how cumbersome is it to create objects with some methods defined on them without it.
function animal(name, numLegs) {
// if you call animal without new keyword, this is the global object.
// if y
this.name = name
this.numLegs = numLegs
}
animal.prototype.greet = function () {
return `I am a ${this.name}, I have ${this.numLegs} legs`
}
Creating instances of animal
:
const lion = new animal("lion", 4)
const octopus = new animal("octopus", 8)
console.log(octopus.greet())
console.log(lion.greet())
console.log(lion.hasOwnProperty("name"))
Now, let's do the same thing using class
class Animal {
constructor(name, numLegs) {
this.name = name
this.numLegs = numLegs
}
greet() {
return `I am a ${this.name}, I have ${this.numLegs} legs`
}
}
const lion = new Animal("lion",4)
const octopus = new Animal("octopus",8)
console.log(lion.greet())
console.log(octopus.greet())
console.log(lion.hasOwnProperty("greet"))