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

--

--

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