Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

JavaScript Static Function Error

When I run this code, I get an error saying: "TypeError: Jerry.greeting is not a function"

class Lion {
  constructor(name,age) {
    this.name = name;
    this.age = age;
  }

  static greeting() {
    return "Hi, my name is " + this.name + " and I am " + this.age + " years old.";
  }
}

var Jerry = new Lion('Jerry',16);
console.log(Jerry.greeting());

1 Answer

Hi Ray,

The reason to use a static function, is that you don't need to instantiate an object from your class. This also means, that you can't call a static function on an object. You always need to call it on the class. This is why static functions are also referred as class functions.

So you have two ways to resolve this. Either you don't use a static function (I think this is what you want here)

function greeting(){
  //...code
}

Or you call the function on the class, but then you can't use the this-keywords, because there is no object, which they could refer to, so you would need to change the rest of your code.

Lion.greeting();