PROTOTYPE in JAVASCRIPT

Photo by Sigmund on Unsplash

What is a prototype?

When another developer keeps coming up and asking you, “What the heck is a prototype?”, Answer it: It’s your father’s head, asking questions. This answer is somewhat ludicrous but quite accurate; it can be understood that prototype is either the template or the parent of an object.

var str = 'abc'; // str is string, its parent is String.prototype

// Duplicate the input string
String.prototype.duplicate = function () {return this + this; }

console.log (str.duplicate ()); // Found duplicate function in prototype
var person = {
firstName: 'Hoang',
lastName: 'Pham',
showName: function () {
console.log (this.firstName + '' + this.lastName);
}
}; // This object has a prototype of Object.prototype

function Person (firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
this.showName = function () {
console.log (this.firstName + '' + this.lastName);
};
}

var otherPerson = new Person ('John', 'Wick'); // This object has a prototype of Person.prototype
// New prototype: Person.prototype is created
// Person.prototype inherits Object.prototype
function Person (firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}

Person.prototype.love = function () {console.log ('XXX')};

var otherPerson = new Person ('John', 'Wick'); // This object has a prototype of Person.prototype
otherPerson.love (); // XXX

What is the prototype used for?

Why does this prototype concept spawn? In JavaScript, there is no class concept, so to inherit the fields/functions of an object, we must use the prototype.

function Person () {
this.firstName = 'Per';
this.lastName = 'son';
this.sayName = function () {return this.firstName + '' + this.lastName};
}

// Write another Constructor Function
function SuperMan (firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}

// I want SuperMan to inherit the properties of Person
// Use prototype to inherit
SuperMan.prototype = new Person ();

// Create a new object with Constructor Function
var sm = new SuperMan ('John', 'Wick');
sm.sayName (); // John Wick. This function inherits from Person's prototype

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Beribey

Beribey

Always be nice to anybody who has access to my toothbrush.