Skip to content

Instantly share code, notes, and snippets.

@anoopelias
Created August 11, 2012 13:40
Show Gist options
  • Save anoopelias/3324518 to your computer and use it in GitHub Desktop.
Save anoopelias/3324518 to your computer and use it in GitHub Desktop.
A snippet to show the idea of prototype object and inheritance in JavaScript
ObjMaker = function() {
this.a = "first";
};
ObjMaker.prototype.b = "second";
var objMaker = new ObjMaker();
ObjMaker.prototype.c = "third";
console.log("objMaker.a " + objMaker.a); // Prints 'first'
console.log("objMaker.b " + objMaker.b); // Prints 'second'
console.log("objMaker.c " + objMaker.c); // Prints 'third'
SubObjMaker = function() {
this.b = "fourth";
this.d = "fifth";
};
SubObjMaker.prototype = new ObjMaker();
SubObjMaker.prototype.c = "sixth";
SubObjMaker.prototype.e = "seventh";
var subObjMaker = new SubObjMaker();
console.log("subObjMaker.a " + subObjMaker.a); // Prints 'first'
console.log("subObjMaker.b " + subObjMaker.b); // Prints 'fourth'
console.log("subObjMaker.c " + subObjMaker.c); // Prints 'sixth'
console.log("subObjMaker.d " + subObjMaker.d); // Prints 'fifth'
console.log("subObjMaker.e " + subObjMaker.e); // Prints 'seventh'
console.log("objMaker.b " + objMaker.b); // Prints 'second'
console.log("objMaker.c " + objMaker.c); // Prints 'third'
console.log("objMaker.d " + objMaker.d); // Prints 'undefined'
console.log("objMaker.e " + objMaker.e); // Prints 'undefined'
@anoopelias
Copy link
Author

This is a running example for the snippet mentioned in the top answer of http://stackoverflow.com/questions/1646698/what-is-the-new-keyword-in-javascript

The idea of creating an object of a class, so that we can subclass it is difficult to digest (Line #18). Well, I guess I have to live with it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment