Skip to content

Instantly share code, notes, and snippets.

@vikingmute
Last active December 17, 2015 09:49
Show Gist options
  • Save vikingmute/5590696 to your computer and use it in GitHub Desktop.
Save vikingmute/5590696 to your computer and use it in GitHub Desktop.
simple klass method to provide OO feature in JS
var Animal = Klass({
init:function(name){
this.name = name;
},
pow:function(){
console.log('pow function is animal only '+this.name);
}
});
var Person = Klass({
init:function(name,sex){
this.name = name;
this.sex = sex;
},
speak:function(){
console.log(this.name)
},
lose:function(){
console.log('another method');
}
},Animal);
function Klass(pros,parent){
var child ;
parent = parent || Object;
child = function(){
parent.apply(this,arguments);
pros.init.apply(this,arguments);
}
child.prototype = new parent();
for(var i in pros){
if(i != 'init'){
if(pros.hasOwnProperty(i)){
child.prototype[i] = pros[i];
}
}
}
return child;
}
var cat = new Animal('lily');
var viking = new Person('v','male');
viking.pow();
viking.speak();
console.log(viking instanceof Person)
console.log(viking instanceof Animal)
console.log(cat instanceof Person)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment