Yes, the first one is a static method
also called class method
, while the second one is an instance method
.
Consider the following examples, to understand it in more detail.
In ES5
function Person(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
Person.isPerson = function(obj) {
return obj.constructor === Person;
}
Person.prototype.sayHi = function() {
return "Hi " + this.firstName;
}
In the above code, isPerson
is a static method, while sayHi
is an instance method of Person
.
Below, is how to create an object from Person
constructor.
var aminu = new Person("Aminu", "Abubakar");
Using the static method isPerson
.
Person.isPerson(aminu); // will return true
Using the instance method sayHi
.
aminu.sayHi(); // will return "Hi Aminu"
In ES6
class Person {
constructor(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
static isPerson(obj) {
return obj.constructor === Person;
}
sayHi() {
return `Hi ${this.firstName}`;
}
}
Look at how static
keyword was used to declare the static method isPerson
.
To create an object of Person
class.
const aminu = new Person("Aminu", "Abubakar");
Using the static method isPerson
.
Person.isPerson(aminu); // will return true
Using the instance method sayHi
.
aminu.sayHi(); // will return "Hi Aminu"
NOTE: Both examples are essentially the same, JavaScript remains a classless language. The class
introduced in ES6 is primarily a syntactical sugar over the existing prototype-based inheritance model.