View Single Post
Old 03-17-2017, 05:58 AM   #1
Registered User
Join Date: Jun 2015
Posts: 246
Default Prototype paradigm

This paradigm makes use of an object’s prototype property, which is considered to be the prototype upon which new objects of that type are created. Here, an empty constructor is used only to set up the name of the class. Then, all properties and methods are assigned directly to the prototype property. Rewriting the previous example, the code looks like this:

function Car() {
Car.prototype.color = “red”;
Car.prototype.doors = 4;
Car.prototype.mpg = 23;
Car.prototype.showColor = function () {
var oCar1 = new Car();
var oCar2 = new Car();
In this code, the constructor (Car) is defined first and contains no code. The next few lines of code define the object’s properties by adding them to the prototype property of Car. When new Car() is called, all the properties of prototype are immediately assigned to the object that was created, meaning that all instances of Car contain pointers to the same showColor() function. Semantically, everything looks like it belongs to an object, so the two problems of the previous paradigms have been solved. As an added bonus, this method allows the use of the instanceof operator to check what kind of object a given variable points to. So the following line outputs true:

Fat Cutter | Hot Shaper | Asthijivak
beingchinmay is offline   Reply With Quote