An example of this implemented in Javascript is as followed:
function Person(age, name, location) {
this.age = age;
this.name = name;
this.location = location; // Note this refers to this specific function. This always refers to the object in which this is called.
}
Person.prototype.getAge = function() {
console.log(this.age + ” years old”);
};
Note in more modern versions of Javascript, this can be rewritten as
Person.prototype.getAge = () => {
console.log(this.age + ” years old”);
}.
let person = new Person(34, Robert, California);
Typing person.getAge() will yield the result “34 years old” in the browser’s console. Similar prototypes can be written to obtain the age and location properties of each instance of the person function.
To read more blog posts like this visit our blog section here.
For a more in-depth discussion on Javascript prototypes, I recommend the book Headfirst: Javascript written by Eric Freemen and Emily Robson. Also, here is a link to a website explaining Javascript prototypes more in depth.
0 Comments