I am new to JavaScript OOP. Can you please explain the difference between the following blocks of code. I tested and both blocks work. What's the best practice and why?
First block:
function Car(name){
this.Name = name;
}
Car.prototype.Drive = function(){
document.write("My name is " + this.Name + " and I'm driving. <br />");
}
SuperCar.prototype = new Car();
SuperCar.prototype.constructor = SuperCar;
function SuperCar(name){
Car.call(this, name);
}
SuperCar.prototype.Fly = function(){
document.write("My name is " + this.Name + " and I'm flying! <br />");
}
var myCar = new Car("Car");
myCar.Drive();
var mySuperCar = new SuperCar("SuperCar");
mySuperCar.Drive();
mySuperCar.Fly();
Second block:
function Car(name){
this.Name = name;
this.Drive = function(){
document.write("My name is " + this.Name + " and I'm driving. <br />");
}
}
SuperCar.prototype = new Car();
function SuperCar(name){
Car.call(this, name);
this.Fly = function(){
document.write("My name is " + this.Name + " and I'm flying! <br />");
}
}
var myCar = new Car("Car");
myCar.Drive();
var mySuperCar = new SuperCar("SuperCar");
mySuperCar.Drive();
mySuperCar.Fly();
Why did the author add Drive
and Fly
methods using prototype
, but doesn't declare them as this.Drive
method inside Car
class and this.Fly
in SuperCar
class?
Why does SuperCar.prototype.constructor
need to be set back to SuperCar
? Is constructor property overridden when prototype
is set? I commented out this line and nothing changed.
Why call Car.call(this, name);
in SuperCar
constructor? Won't properties and methods of Car
be 'inherited' when I do
var myCar = new Car("Car");