Difference between parent.call (arguments) and child.prototype = new parent (arguments)?

I am trying to get my head completely wrapped up with prototype inheritance and the Javascript inheritance system.

I am trying to figure out what is the difference between these two examples. I'm going to guess that this is due to the prototype inheritance chain, but I'm having trouble finding information related to the two.

Example 1 - calling ()

function Vehicle(wheels) {
    this.wheels = wheels;
}

function Car(doors) {
    this.doors = doors;
    Vehicle.call(this,4);
}

Example 2 - prototype

function Vehicle(wheels) {
    this.wheels = wheels;
}

function Car(doors) {
    this.doors = doors;
}
Car.prototype = new Vehicle(4);
+3
source share
2 answers

In the first example, you initialize your object Carto have all the same properties of the new object Vehicle. However, this is not "real" inheritance, but as follows:

var car = new Car(2);
car instanceof Vehicle; // => false

: instanceof . :

var car = new Car(2);

Vehicle.prototype.drive = function() {
  console.log('vroom!');
};

car.drive(); // throws

, : Car Vehicle.

, .


, , , , Vehicle, , Car ( ).

, : 4 wheels Vehicle, . , , :

function Vehicle(wheels, color) {
  this.wheels = wheels;
  this.color = color;
}

:

function Car(doors, color) {
  this.doors = doors;
  Vehicle.call(this, 4, color);
}

Car.prototype = new Vehicle();

, Car Car Vehicle, Car. , color .

:

function Car(doors, color) {
  this.doors = doors;
  this.color = color;
}

Car.prototype = new Vehicle(4, null);

.

+2

( proto, ), .

, :

enter image description here

, , :

  • carsObj , Car . Vehicle.call(this,4); , Car.
  • , ; (, ). , .
  • .

- , .

, , :

enter image description here

. Car , Car. Car.prototype = new Vehicle(4);.

Car , . , JavaScript .

, Car Vehicle. .

; :

function Vehicle(wheels) {
   this.wheels = wheels;
}

function Car(doors) {
   this.doors = doors;
   Vehicle.call(this, 4)
}

Car.prototype = Object.create(Vehicle);

, Car , .

+1

All Articles