object oriented in js

通过function的prototype实现面向对象
Function.prototype.extend=function(superCls){
var self_prototype=this.prototype;
var super_prototype=superCls.prototype;
this.super=super_prototype;
self_prototype.super=super_prototype;
for(var key in super_prototype){
if(!self_prototype[key]){
self_prototype[key]=super_prototype[key];
}
}
return this;
}
Function.prototype.body=function(obj){
for(var p in obj){
this.prototype[p]=obj[p];
}
return this;
}

以下是测试代码
var Animal=function(){
alert("Animal name is "+this.name);
}.body({
name:"generic animal",
sing:function(){
alert(this.name+" sing");
}
});
var Chiken=function(){
Chiken.super.constructor.apply(this, arguments);// or this.super.constructor.apply(this, arguments);
alert("Chiken name is "+this.name);
}.body({
name:"chiken",
sing:function(sth){
alert(this.name+" sing ji ji gou " + sth);
}
}).extend(Animal);
var Duck=function(){
Duck.super.constructor.apply(this,arguments);
alert("Duck name is "+this.name);
}.body({
name:"duck",
sing:function(){
Duck.super.sing.apply(this,arguments)
alert(this.name+" sing gua gua");
}
}).extend(Animal);
var TomDuck=function(){
TomDuck.super.constructor.apply(this,arguments);
alert("TomDuck name is "+this.name);
}.body({
name:"Tom duck",
sing:function(){
alert(this.name+" what's fuck sing");
}
}).extend(Duck);
var tomDuck=new TomDuck();
tomDuck.sing();
var duck=new Duck();
duck.sing("....");

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326941174&siteId=291194637