JavaScript's prototype is an essential concept that allows programmers to achieve inheritance, that is, to add a prototype property to any created function.
Every object in JavaScript has a built-in property called prototype, which is an invisible built-in object in Javascript.
Prototypes are part of JavaScript's inheritance model, and every object in JavaScript has a prototype object, from which it inherits properties and methods or functions.
Prototypes can be used to access properties and methods of prototype objects, allowing objects to inherit properties and methods from their prototypes, allowing JavaScript objects to inherit features from each other.
The prototype object can create new variables and functions, and the variables and methods available in the inherited prototype object can be accessed and modified as desired.
The prototype object can be understood through several examples, and it is important to have a basic understanding of the 'this' reference in JavaScript before understanding the prototype object.
We create a function Constructor in JavaScript. This is a function that accepts a series of input parameters that use the reserved word this to define a series of properties or methods that will form a custom object.
function Employee(name, age, gender){
this.name = name;
this.age = age;
this.gender = gender;
}
We can create a constructor function with internal methods:
function Employee(name, yearBirth, gender) {
//Private methods
var age = function(yearBirth) {
var current = new Date().getFullYear();
return (current - yearBirth);
};
//Public properties
this.name = name;
this.yearBirth = yearBirth;
this.age = age(this.yearBirth);
this.gender = gender;
//Public methods
this.showMe = function() {
document.getElementById('show').innerHTML =
'Hello, my name is '+this.name+' my age is '+this.age+' years old';
};
}
In JavaScript, instances are created from the intrinsic object Object by constructor functions using the new Object() initializer.
var employee1 = new Employee('John', 2001, 'Male');
We can add properties and methods to a constructor function.
For example, to the "Employee" constructor function we can add the "city" property and the "showAll" method by prepending the "prototype" keyword:
Employee.prototype.city = 'London';
Employee.prototype.showAll = function(valueId){
document.getElementById(valueId).innerHTML =
'Name: '+this.name+', year birth: '+this.yearBirth+', age: '+this.age+', gender: '+this.gender+' city:'+this.city+' house:'+this.house;
}
We can also add properties to the "employee1" instantiated object. In the following example we add the "house" property:
employee1.house = 'yes';
If we look at the browser console, pressing the F12 button, for example, in Google Chrome.
By typing the name of the constructor function into the browser console, we can see the list of available methods, including "prototype".
Tips on SEO and Online Business
Next Articles
Previous Articles