-1
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?

Michael
  • 1,537
  • 6
  • 20
  • 42
  • 1
    What does not work? What is the error message? Without a problem statement, every code is correct. – Bergi Jun 22 '16 at 23:38

3 Answers3

1

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');
Zohaib Ijaz
  • 21,926
  • 7
  • 38
  • 60
1

You can do both! The difference in

class Person(...) {
    ...
}

Person.myFunction = function(val) { // This is a public function
    return val;
}

Person.prototype.myFunction = function(val) { // This is a private function
    return val;
}

is how you access it.

Access the public function :

var r = Person.myFunction("Hello!");
console.log(r);

Access the private function:

var person1 = new Person(...);
var r = person1.myFunction("Hello!");
console.log(r);

See also this question.

Community
  • 1
  • 1
0

Actually it works, but firstly you need to create an instance of Person to be able call its methods. For example:

var john = new Person("John");
console.log(john.greetExtraTerrestrials("predator"));
Telman
  • 1,444
  • 1
  • 9
  • 12