Abbas Shah
Abbas Shah

Reputation: 13

How to fix this (is not a function) error?

This is a snippet of code related to JavaScript project. I have declared the function in my Class. But when i invoke the function with an argument(i am passing an array of elements as an argument), it returns the Uncaught TypeError: School.pickSubstituteTeacher is not a function.


class School {

  pickSubstituteTeacher(substituteTeachers){
  let randomTeacher = Math.floor(  Math.random() * substituteTeachers.length);
   return substituteTeachers[randomTeacher];
   }
}
School.pickSubstituteTeacher(['Dave', 'John', 'Henry']);

I expect the output to be a random Teacher selected from this array of three elements.

Upvotes: 1

Views: 701

Answers (2)

CertainPerformance
CertainPerformance

Reputation: 370619

What you have there is a method on the prototype, not on the class itself. If you had an instance of School like

const school = new School();
school.pickSubstituteTeacher(...

your code would work, but you're trying to call it as a static method, a method directly on the class, rather than on School.prototype.

Either make an instance first, or make it a static method with the static keyword:

class School {
  static pickSubstituteTeacher(substituteTeachers){

If a class-related function needs information about an instance (for example, maybe access this.teachers to get a list of teacher names), it needs to be a method on the prototype, but that's not the case here. If a class-related function doesn't need information about an instance (like in this case), you can make the method static, if you want. (in that situation, whether you use a normal method or a static method depends on the circumstances)

Upvotes: 1

Maheer Ali
Maheer Ali

Reputation: 36564

You need to create an instance and then apply method on it.

class School {
  pickSubstituteTeacher(substituteTeachers){
     let randomTeacher = Math.floor(  Math.random() * substituteTeachers.length);
     return substituteTeachers[randomTeacher];
  }
}
const instance = new School()

console.log(instance.pickSubstituteTeacher(['Dave', 'John', 'Henry']));

Or if you want a static method(a method which will be on the class not instance of class) then use static before the method.

class School {

  static pickSubstituteTeacher(substituteTeachers){
      let randomTeacher = Math.floor(  Math.random() * substituteTeachers.length);
      return substituteTeachers[randomTeacher];
   }
}
console.log(School.pickSubstituteTeacher(['Dave', 'John', 'Henry']));

Upvotes: 3

Related Questions