[原]JavaScript学习笔记(六.继承)
1.单继承,使用call()方法
?
//父类function Father(name,age){this.Name = name;this.Age = age;this.Intro = function(){alert("hello, I am" + this.Name);}}//子类function Child(name,age){Father.call(this,name,age);//实现继承!并且调用父类的构造方法,this是当前对象 // Father.apply(this, new Array(name,age));//跟call一样的功能this.Code = function(){alert("I am coding");}}var father = new Father("father",50);var child = new Child("child",23);father.Intro();child.Intro();//子类调用继承自父类的方法child.Code();//子类调用自己的方法?
2.单继承?
?
//父类function Father(name,age){this.Name = name;this.Age = age;this.Intro = function(){alert("hello, I am" + this.Name);}}//子类function Child(name,age){this.Constructer = Father;//指定方法为上面那个父类的那个方法,跟下面的方法合起来实现继承this.Constructer(name,age); //调用该方法:注意调用的时候,是Child对象调用,那么调用完,Child的2个属性也就赋值了,而且多了1个方法delete this.constructor; // 删除这个方法,是因为不想覆盖父类的相关方法和属性?this.Code = function(){alert("I am coding");}}var father = new Father("father",50);var child = new Child("child",23);father.Intro();child.Intro();//子类调用继承自父类的方法child.Code();//子类调用自己的方法?
3.多继承
?
//父类1function Father(name,age){this.Name = name;this.Age = age;this.Intro = function(){alert("hello, I am" + this.Name);}}//父类2function Father_2(pay){this.Pay = pay;this.showPay = function(){alert("your pay is " + this.Pay);}}//子类function Child(name,age,pay){this.Constructer = Father;//指定方法为上面那个父类的那个方法this.Constructer(name,age); //调用该方法:注意调用的时候,是Child对象调用,那么调用完,Child的2个属性也就赋值了,而且多了1个方法delete this.Constructor; // 删除这个方法,是因为不想覆盖父类的相关方法和属性?this.Constructer2 = Father_2;this.Constructer2(pay);delete this.Constructer2;this.Code = function(){alert("I am coding");}}var father = new Father("father_1",50);var fater_2 = new Father_2(5000);var child = new Child("zxh",23,10000); //I am coding. father.Intro();//hello, I am father'_1child.Intro();//调用从第一个父类继承的方法hello,I am zxh. child.Code();//I am codingchild.showPay();//调用从第二个父类继承的方法 your pay is 10000?
?
4.多继承2
?
//父类构造方法function Father(name,age){this.Name = name;this.Age = age;}//父类的方法Father.prototype.Intro = function(){alert("I am father");}//子类构造方法function Child(name,age){Father.call(this,name,age);//调用父类构造方法,得到各个属性}Child.prototype = new Father(); //实现继承//定义子类自己的方法Child.prototype.Code = function(){alert("I am coding !");}//覆盖父类的方法[如果不指定上面的继承,其实也就相当与自己新定义一个一样]Child.prototype.Intro = function(){alert("I am " + this.Name);}var father = new Father();var child = new Child("zxh",23);father.Intro(); //父类调用自身方法child.Intro(); //子类调用覆盖父类的方法child.Code();//子类调用自己定义的方法?