面向对象的继承方式有三种:
1、原型链实现继承
//定义一个父类
function Parent() {
this.pv="parent";
}
Parent.prototype.showParent=function() {
alert(this.pv);
}
//定义一个子类
function Son() {
this.sv="Son";
}
//使用原型链来实现继承
Son.prototype= new Parent();
Son.prototype.showSon=function() {
alert(this.sv);
}
var s1= new Son();
s1.showParent();
s1.showSon();
但是这种方式存在一些问题:
1、无法从子类中调用父类的构造函数, 这样就没有办法把子类中属性赋值给父类。
2、父类中属性是在子类的原型中的,这违背了我们前面所讲的封装的理念( 属性在对
象中,方法在原型中), 会出现前面值的混淆问题。
2、基于伪装实现继承
//定义一个父类
function Parent() {
this.pv="parent";
}
//定义一个子类
function Son() {
this.sv="Son";
Parent.call(this);//注意:此时的this指的是Son的对象
//那么就是Son对象调用Parent函数
}
var s1= new Son();
alert(s1.pv);
除了call方法外,还可利用apply方法,两者不同之处在于第二个参数,call是参数列表,而apply是参数数组。
这种方式可以解决原型链继承所产生的问题,但同样存在着其他问题:
由于使用伪造的方式继承,子类的原型不会指向父类,所以父类中写在原型中的方法不
会被子类继承, 所以子类调用不到父类的方法。
解决的办法就是将父类的方法放到子类中来,但是这样的又违背了封装的理念。
3、基于组合实现继承
function Parent(name) {
this.name=name;
this.friends=["老许","老孙"];
}
Parent.prototype.parentSay=function() {
alert(this.name+"---->"+this.friends);
}
//定义一个子类
function Son(name,age) {
this.age=age;
Parent.apply(this,[name]);
}
//使用原型链来实现继承
Son.prototype= new Parent();
Son.prototype.sonSay=function() {
alert(this.name+"*******==="+this.age);
}
var s1= newSon("老王",18);
s1.friends.push("老刘");
s1.parentSay();
s1.sonSay();
var s2 = newSon("老李",28);
s2.parentSay();
s2.sonSay();
这种方法就可以同时解决以上两个问题。
ECMAScript6—面向对象
ES6中利用class来申明类。
/**
*使用class关键字申明一个类,类名为Parent
*/
class Parent {
//constructor方法就是Parent的构造方法
//可以使用它来初始化Parent类的属性
constructor(name,age) {
this.name=name;
this.age=age;
}
//直接申明Parent类的方法,say
say() {
returnthis.name+"---->"+this.age;
}
//使用static关键字申明静态方法
//注意静态方法属于类,而不属于对象
static sayHello() {
alert("Hello老王");
}
}
//错误
//new Parent().sayHello();
//正确,该方法数据类
//Parent.sayHello();
在ES6中利用extend来实现继承:
//使用extends来申明Son类继承Parent类
class Son extends Parent {
constructor(name,age,sex) {
//使用super关键字表示父类(超类)
super(name,age);
this.sex=sex;
}
sayWord() {
alert(this.sex+"----->"+this.name+"----------"+this.age);
}
//使用父类中的同名方法,会覆盖父类方法(override)
say() {
return"哈哈";
}
}
let p1= new Son("阿里巴巴",15,"男");
//p1.sayWord();
alert(p1.say());
网友评论