Prototype Example

Small prototype Example

by jimmyt1001

JavaScript

var x = function(J){ //Every function expression is a constructor
	this.i = 0; // Setting default value for the "property" i
	this.J = J; //passing j above

	//Prototype method
	x.prototype.getJ = function(){ // {objectName}.prototype.{methodName}
		return this.J;
	};

};

//Create instances of  x using keyword new. Creat an object from it

var x1 = new x(1); 
var x2 = new x(2);

// x1 and x2 do not have their own method getJ include inside
//Instead whenever x1 and x1 is called it gets looked up into the prototype chain looks into its parents
//to see if it can find that method in a protype. It finds it and then it uses it
//This way the obects are much smaller. There is no need to have all of the methods inside of an object. You can use it from the parents prototupe
alert(x1.getJ());
alert(x2.getJ());