Search code examples
javascriptscopebindecmascript-5

Javascript method in Function Error with "is not a function"


I've been learning basic Javascript concept with class. I'm trying it with ES5 syntax.

By the way, I'm stuck with this problem. I defined a class with function declaration. And Defined a method in that class.

const Vehicle = function() {
  this.passengers = [];
  console.log('Vehicle created');

  const addPassenger = function(p) {
    this.passengers.push(p);
  }
}

const v = new Vehicle();

v.addPassenger("Frank");
v.addPassenger("Zim");
console.log(v.passengers);

But when I call it with its instance, I got the error. I think the problem is bind...But I have no idea where and which one should I bind.

Thank you!


Solution

  • You are currently only declaring the addPassenger function as a constant inside the function.

    To "make the function part of class", use this

    this.addPassenger = function(p) {
    ////
    }