Last active
December 17, 2015 09:49
-
-
Save vikingmute/5590696 to your computer and use it in GitHub Desktop.
simple klass method to provide OO feature in JS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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