PROTOTYPE in JAVASCRIPT

Photo by Sigmund on Unsplash

What is a prototype?

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?

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

--

--

--

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

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Clone of Gab.com

React HTML parser

Memoization in Javascript

As We Begin to Form

Only here so I won’t get fined.

Javascript based E2E test framework — Codeceptjs — Part I — Basics

Why choose React for frontend development?

KnockoutJs and Magento 2 uiComponent

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.

More from Medium

Glance at the JavaScript arrow function

Fun with Promises in Javascript

Loading Javascript Asynchronously (Defer vs Async)

Write beautiful and Elegant Javascript code with short-circuit evaluation.