Difference between Class.method and Class.prototype.method
JavaScript is an object-oriented programming language, but unlike its peers (which are class-based), JavaScript is a prototype-based language. It means that in JavaScript, you can create an object (prototype object) that acts as a template for new objects. These new objects can be provided with new properties either when you create them or at run time.
There are two ways to add new methods to an object.
Class.method: The Class.method is static and has no relation with any instance of the class. The class method must be called using the class name. Only one instance of this function exists in the memory.
Example: This example shows the use of the above-explained method.
Javascript
<script>
function User(userName) {
this .userName = userName;
};
User.message = function () {
console.log( "Login successful" );
};
const newUser = new User( "GFG" );
User.message();
</script>
|
Output:
Login successful
Class.prototype.method: The Class.prototype.method is created which is related to the instance of the object. It is called using the object instance name. Each instance of the class will have its own copy of this method.
Example: This example shows the use of the above-explained method.
Javascript
<script>
function User(userName) {
this .userName = userName;
};
User.message = function () {
console.log( "Login successful" );
};
User.prototype.greet = function () {
console.log( "Welcome " + this .userName);
};
const newUser = new User( "GFG" );
User.message();
newUser.greet();
</script>
|
Output:
Login successful
Welcome GFG
The above code can be written using JavaScript classes that were introduced in ECMAScript 2015.
Javascript
<script>
class User {
constructor(userName) {
this .userName = userName;
}
static message = function () {
console.log( "Login successful" );
};
greet = function () {
console.log( "Welcome "
+ this .userName);
};
}
const newUser = new User( "GFG" );
User.message();
newUser.greet();
</script>
|
Output:
Login successful
Welcome GFG
JavaScript classes are syntactical sugar over JavaScript’s prototype-based approach.
Last Updated :
18 Jan, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...