// declared class vehicle
function Vehicle(make,model,year){
this.make=make
this.model=model
this.year=year
}
// 2 - Add a function to the Vehicle prototype called start which returns the string //"VROOM!"
Vehicle.prototype.start=function(){
return "VROOM!"
}
// declared child class car
function Car(make,model,year){
Vehicle.apply(this,arguments)
this.numWheels=4
}
// assigning the constructor
Car.prototype.constructor=Object.create(Vehicle.constructor)
// changing the pointing of constructor back to car
Car.prototype.constructor=Car;
var sedan=new Car("Tractor", "John Deere", 1999)
console.log(sedan.start())
//sedan.start() gives error but if i declare it inside vehicle class does not
To get Car()
to inherit the methods defined on Vehicle()
's prototype, you can simply use:
Car.prototype = Object.create(Vehicle.prototype);
Here Object.create()
method is used to create a new object and make it the value of Car.prototype
. The new object has Vehicle.prototype
as its prototype and will therefore inherit all the methods available on Vehicle.prototype
. So, there is no need to use the below logic:
// assigning the constructor
Car.prototype.constructor=Object.create(Vehicle.constructor)
DEMO:
// declared class vehicle
function Vehicle(make, model, year) {
this.make = make
this.model = model
this.year = year
}
// 2 - Add a function to the Vehicle prototype called start which returns the string //"VROOM!"
Vehicle.prototype.start = function() {
return "VROOM!"
}
// declared child class car
function Car(make, model, year) {
Vehicle.apply(this, arguments)
this.numWheels = 4
}
Car.prototype = Object.create(Vehicle.prototype);
Car.prototype.constructor = Car;
var sedan = new Car("Tractor", "John Deere", 1999)
console.log(sedan.start())
A better approach using Classes
:
ECMAScript 2015 introduces class syntax to JavaScript as a way to write reusable classes using easier, cleaner syntax, which is more similar to classes in C++ or Java. Here we'll convert the Vehicle and Car example from prototypal inheritance to classes, to show you how it's done.
DEMO:
class Vehicle {
constructor(make, model, year) {
this.make = make;
this.model = model;
this.year = year;
}
start() {
return "VROOM!"
};
}
class Car extends Vehicle {
constructor(make, model, year) {
super(); // Now 'this' is initialized by calling the parent constructor.
}
bonet() {
return "VROOM2!"
};
}
var sedan = new Car("Tractor", "John Deere", 1999)
console.log(sedan.start())
console.log(sedan.bonet())