Skip to content

Instantly share code, notes, and snippets.

@zacksleo
Last active January 4, 2016 10:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save zacksleo/8610926 to your computer and use it in GitHub Desktop.
Save zacksleo/8610926 to your computer and use it in GitHub Desktop.
JavaScript Class
/**
* Combination Constructor/Prototype Pattern
*/
//constructor
function Something(name){
//properties
this.name = name;
}
//prototype
Something.prototype = {
//methods
sayhello:function(){
console.log('hello '+this.name);
},
sayhi:function(){
console.log('hi '+this.name);
}
}
var obj = new Something('souparno');
var obj2 = new Something('zacks');
/********************EOF*******************************/
/**
* Dynamic Prototype Pattern
*/
//constructor
function Something(name){
//properties
this.name = name;
//methods
if(typeof this.sayhello != "function"){
Something.prototype.sayhello = function(){
console.log('hello '+this.name);
};
}
if(typeof this.sayhi != "function"){
Something.prototype.sayhello = function(){
console.log('hi '+this.name);
};
}
}
var obj = new Something('souparno');
var obj2 = new Something('zacks');
@souparno
Copy link

souparno commented Feb 2, 2014

(function(){
this.Class=function(){};
Class.Create=function(property){
var _property={};
for(var p in property)
{
if(p === "init") this.Class=property[p];
else _property[p]=property[p];
};
this.Class.prototype=_property;
return this.Class;
};
}());

var something=Class.Create({

init:function(){
    console.log("The constructor says hello"); 
},

sayhello:function(){
    console.log("hello there"); 
                   },
sayhi:function(){
    console.log("hiiiiiii");
                }

});

var obj=new something();
obj.sayhello();
obj.sayhi();

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