1

I am a newbie in programming who is currently learning OOP in javascript. I wrote a simple code showing the prototypal inheritance by calling a parent constructor. But it is showing error "InternalError: too much recursion"

Here is the code I wrote:

function Vehicle() {
  this.name = "Vehicle";
}

Vehicle.prototype = {
  drive: function() {
    return this.name + " drives forward ";
  },

  stop: function() {
    return this.name + " stops"
  }
};

function Truck(name) {
  this.name = name;
}

Truck.prototype = Vehicle.prototype;
Truck.prototype.drive = function (){
  let msg = Vehicle.prototype.drive.apply(this);
  return msg += "through field"
}

let jeep = new Truck("Jeep");

console.log(jeep.drive())

And when I changed Truck.prototype = Vehicle.prototype; to Truck.prototype = new Vehicle(); the code worked.

Can anybody explain in simple terms what is going on? and while we are on the topic I also don't understand what apply()does? can you point me towards some good resources.

Thanks in advance.

  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply – Bergi May 17 '20 at 14:37
  • Welcome to SO. Try to ask a single and well-focused question. Asking for "some good resources to understand X" is considered off-topic on this side (see [What topics can I ask about here](https://stackoverflow.com/help/on-topic) Also try to search first to see whether your question has already been answered. – Ivo Mori May 17 '20 at 15:12

0 Answers0