22
loading...
This website collects cookies to deliver better user experience
inheritance
in Object-oriented programming? Inheritance allows for one class to inherit (or obtain) the attributes and methods of another class. The class whose properties and methods are inherited is known as the Parent
class.drive
method.function Car(){}
Car.prototype = {
constructor: Car,
drive: () => {
console.log("Vroom vroom")
}
}
function Motorcycle() {}
Motorcycle.prototype = {
constructor: Motorcycle,
drive: () => {
console.log("Vroom vroom")
}
}
Vehicle
and removing the drive method from both Car and Motorcycle and putting it in Vehicle.//child object
function Car(){}
Car.prototype = {
constructor: Car,
drive: () => {
console.log("Vroom vroom")
}
}
//child object
function Motorcycle() {}
Motorcycle.prototype = {
constructor: Motorcycle,
drive: () => {
console.log("Vroom vroom")
}
}
// parent object
function Vehicle(){
}
Vehicle.prototype = {
constructor: Vehicle,
drive: () => {
console.log("Vroom vroom")
}
}
Vehicle
object. We can create a new instance of Animal simply by using a the methodObject.create(obj)
. This will create a new object and set obj
as the new object's prototype. Car.prototype = Object.create(Vehicle.prototype)
let honda = new Car();
console.log(honda.drive());
//output: "Vroom vroom"
Car
is now an instance of Vehicle. When we create a new Car
object and store it into variable honda. honda
now inherits all of Vehicle
's properties and thus can perform the drive()
method.