Leran JavaScripts
JavaScript Object Prototypes
All JavaScript objects inherit properties and methods from a prototype.Example:
function Person(first, last, age) {
this.firstName = first;
this.lastName = last;
this.age = age;
}
const myFather = new Person("John", "Doe", 28);
const myMother = new Person("Sally", "Rally", 48);
To add a new property to a constructor, you must add it to the constructor function:
Person.nationality = "English";
function Person(first, last, age) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.nationality = "English";
}
The JavaScript prototype property also allows you to add new methods to objects constructors:
Example::
function Person(first, last, age) {
this.firstName = first;
this.lastName = last;
this.age = age;
}
Person.prototype.name = function() {
return this.firstName + " " + this.lastName;
};