-
- functionClassA(id){
- this.id=id;
- this.sayId=function(){
- alert(this.id);
- };
- }
-
- functionClassB(id,name){
- this.newMethod=ClassA;
- this.newMethod(id);
- deletethis.newMethod;
-
- this.name=name;
- this.sayName=function(){
- alert(this.name);
- };
- }
-
- functionClassB(id,name){
- ClassA.call(this,id);//this指向ClassB的对象
-
- this.name=name;
- this.sayName=function(){
- alert(this.name);
- };
- }
-
- functionClassB(id,name){
- ClassA.apply(this,newArray(id));//this指向ClassB的对象
-
- this.name=name;
- this.sayName=function(){
- alert(this.name);
- };
- }
-
- functionClassA(id){
- this.id=id;
- }
- ClassA.prototype.sayId=function(){
- alert(this.id);
- };
- functionClassB(id,name){
- ClassA.call(this,id);
- this.name=name;
- }
- ClassB.prototype=newClassA();
- ClassB.prototype.sayName=function(){
- alert(this.name);
- }
- varo={};//o不是对象
- o.eat=function(){return"3432";};
- o.pass=function(text){this.name=text;};
- varHuman=newFunction();//是Function而不是function
- Human.prototype=o;
- vartt=newHuman();
使用prototype与apply实现类继承的模拟。用prototype把父类的公有方法与公有变量加入到子类中去。在子类构造方法中,用apply执行父类的构造方法。
- functionParent()
- { //父类
- this.pname="parentName";//父类公有变量
- this.say=function(){alert(this.pname)};//父类公有方法
- this.tell=function(){alert(this.pname+"tell")};//父类公有方法
- }
- functionSon()
- {
- //以下两句要先执行,不然不能完成方法覆盖
- Son.prototype=newParent();//得到父类的公有变量与公有方法
- Parent.apply(this);//调用父类的构造函数
- this.sname="sonName";//子类公有变量
- this.say=function(){alert(this.sname)};//子类公有方法,覆盖了父类的say方法
- this.talk=function(){alert(this.sname+"talk")};//子类公有方法
- }
用js实现自已定义的类体系
- varPerson={//定义名为Person的类
- Create:function(name,age){//Create指明构造函数
- this.name=name;//定义类公有变量
- this.age=age;//定义类公有变量
- },
- SayHello:function(){//定义公有方法
- alert("Hello,I'm"+this.name);
- },
- HowOld:function(){//定义公有方法
- alert(this.name+"is"+this.age+"yearsold.");
- }
- };
- functionFun(){Person.Create("dd","ss");};//定义了一个名为Fun的函数,
- Fun.prototype=Person;//让Fun拥有Person类的成员
- //一旦执行了Fun函数,就执行了Person.Create方法,
- //Person.Create方法一执行,Person就有了公有变量name与age
- //当Person有了公有变量时,由于Fun中有Person类成员,因此Fun也就有了name变量
- //与age变量。
- varp=newFun();
- p.SayHello();//显示“Hello,I'mdd”,这表明了p具有了变量name与age.
新的基本对象创建
- varTObject={
- IsA:function(aType)
- {
- varself=this;
- if(self.Type==aType)
- returntrue;
- self=self.Type;
- while(self)
- {
- if(self.ParentType==aType)
- returntrue;
- self=self.ParentType;
- };
- returnfalse;
- }
- };
- functionClass(aBaseClass,aClassDefine)
- {
- functionclass_()
- {
- this.ParentType=aBaseClass;
- for(varmemberinaClassDefine)
- this[member]=aClassDefine[member];
- };
- class_.prototype=aBaseClass;
- returnnewclass_();
- };
- functionNew(aClass,aParams)
- {
- functionnew_()
- {
- this.Type=aClass;
- if(aClass.create)
- aClass.create.apply(this,aParams);
- };
- new_.prototype=aClass;
- returnnewnew_();
- };
- Person2=Class(TObject,{
- T2:'sdfsd',
- create:function(name,age)
- {
- this.name=name;
- this.age=age;
- },
- sayHello:function()
- {
- alert(this.name+''+this.age);
- }
- });