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

A Simple introduction to recursion

What is UseState() ?

Useful to developer Object orient programming, pure and impure function, getter, setter, prototype…

Start Testing Your React Applications

About some knowledge to JavaScript

Data Extraction With Destructuring in Javascript

Learn Cypress.io the hard way: Manipulate URLs and links

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

Currying in JavaScript

JavaScript Promises

All you need to know about arrays in JavaScript

History/Origin of JavaScript