Michael Michael - 5 months ago 26
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

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

Person.greetExtraTerrestrials('ABC');