Skip to content

Instantly share code, notes, and snippets.

@k33g
Created February 12, 2011 10:44
Show Gist options
  • Save k33g/823684 to your computer and use it in GitHub Desktop.
Save k33g/823684 to your computer and use it in GitHub Desktop.
une autre version de classe en js avec héritage
var mum = (function () {
var mummy = {};
mummy.Class = function(definition){
var that = function(){},m,mb,mbs,mbc,inst;
for(m in definition){
switch(m){
case 'Members':for(mb in definition.Members){that.prototype[mb] = definition.Members[mb];}break;
case 'Static':for(mbs in definition.Static){that[mbs] = definition.Static[mbs];}break;
case 'Extends':that.prototype = new definition.Extends;break;
case 'Init':
for(mbc in definition.Init){
that.prototype.typeName = mbc;
if(definition.Init[mbc]!=null){
that.prototype[mbc] = definition.Init[mbc];
that.getInstance = function(){
inst = new that;
inst[mbc].apply(inst,arguments);
return inst;
};
}else{
that.getInstance = function(){
throw 'abstract class';
};
}
}
break;
default:/*nothing*/break;
}
}
return that;
}
return mummy;
}());
@k33g
Copy link
Author

k33g commented Feb 14, 2011

Use it like that :

    var Model = new mum.Class({
        Members:{
            id:0
        },
        Init:{
            Model:null /*abstract*/
        }
    });

    var Human = new mum.Class({
        Extends:Model,
        Members:{
            firstName:"John",
            lastName:"Doe",
            sex:"unknown"

        },
        Init:{
            Human:function(fname,lname){
                //this is the constructor
                this.firstName = fname;
                this.lastName = lname;
                this.id = Human.Counter;
                Human.Counter+=1;
                Human.List.push(this);
            }
        },
        Static:{
            Counter:0,
            List:[]
        }
    });

    var bob = Human.getInstance("Bob","Morane");
    var lara = Human.getInstance("Lara","Croft");

    console.log(Human.List);
    console.log(Human.Counter);

@k33g
Copy link
Author

k33g commented Feb 14, 2011

And this is possible too :

    Model.prototype.hello = function(){console.log("Hello World !!!");}
    bob.hello(); /*bob says "Hello World !!!"*/

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