Michael Michael - 1 year ago 98
Javascript Question

Creating a Class Method

function Person (firstName= "John", lastName = 'Doe', age = 0, gender = 'Male'){
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.gender = gender;
this.sayFullName = function() { return this.firstName + " " + this.lastName };

Person.prototype.greetExtraTerrestrials = function(raceName) {
return `Welcome to Planet Earth ${raceName}`;

What is wrong with this code? Doesn't it create a class method called 'greetExtraTerrestrials'?

It is from codewars.com and driving me crazy! Thank you!

Answer Source

Don't place that function on prototype, place that on Class itself like

Person.greetExtraTerrestrials = function(raceName) { 
    return `Welcome to Planet Earth ${raceName}`;

and call it like

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download