Last Updated: September 09, 2019
·
477
· adjavaherian

Prototypes. Way cooler than the games.

Here's some vanilla JavaScript that everybody should know. I'm not a huge fan of Prototypes, because personally, I find it a bit confusing to read. But I'm also slightly slysdeksic. But for most people JavaScript prototypes should be as simple as this:

Prototypes are a way to extend objects with useful functions.

Technically, when you extend a prototype of an object with a function, you are creating a pointer to that function which travels down the prototype chain of all instances of that object until or unless it is overridden. So, from a memory and efficiency perspective, this is the way to go. You are not creating these methods in the object constructor, so new objects created with the same constructor are not using the memory required for the prototype.

This example creates a vanilla object and adds new methods to its prototype chain both before and after instantiation of new objects based on the Mult class.

//Create the basic object constructor
function Mult(){
    this.x;
    this.y;
};

//Extend the Mult object with the square protoype
Mult.prototype.square = function(x,y){
    this.x = x;
    this.y = y;
    return (x*y)*2;
};

//Define the cube func-tion
function cube(x,y){
    this.x = x;
    this.y = y;
    return (x*y)*3;
};

//Extend the Mult object with the cube function
//This is actually creating the cube property of Mult
Mult.prototype.cube = cube;

//Create a new MyMult object based on the Mult class/object
MyMult = new Mult();

//You can even add prototypes after objects have been instantiated
Mult.prototype.showArgs = function(){
    return this.x + ' , ' + this.y;
};


MyMult.square(2,5); // return 20
MyMult.cube(2,6);   // return 36
MyMult.showArgs();   // return '2, 6'

I hope this example clearly demonstrates using prototypes.
Please leave me a comment if you feel I've forgotten something.

Peace,

ad

[MDN on OOJS] https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript