简体   繁体   中英

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.

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'])); 

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM