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> // Constructor function function User(userName) { this .userName = userName; }; // Static function User.message = function () { console.log( "Login successful" ); }; // Creating an instance of User // using new keyword const newUser = new User( "GFG" ); // Message method accessed with User 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" ); }; // Instance method User.prototype.greet = function () { // can access object properties // using 'this' keyword console.log( "Welcome " + this .userName); }; const newUser = new User( "GFG" ); User.message(); // Instance method being accessed // using instance variable 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> // JavaScript class class User { constructor(userName) { this .userName = userName; } // Corresponds to User.message() static message = function () { console.log( "Login successful" ); }; // Corresponds to User.prototype.greet() 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.