继承
继承分为原型链继承、构造函数继承、组合式继承
function person(name){
this.name=name;
this.course=["英语","高数"];
}
person.prototype.say=function(){
return "hi";
}
原型链继承:
function student(age){
this.age=age;
}
student.prototype=new person();
student.prototype.eat=function(){
return "foot";
}
var s1=new student();
s1.course.push("体育");//修改了person的course数组,以后再实例化student时 ,course数组就不是默认的值而是修改过的值。父对象的属性可以被任何实例进行修改。
var s2=new student("dxy");
console.log(s2.name);//undefined, 实例化的子对象不能向父对象传参
构造函数继承:子对象只能访问父对象构造函数里的属性和方法,无法继承父对象的原型对象
function student(age,name){
person.call(this,name);
this.age=age;
this.name=name;//这个新增的属性一定要放在借用构造函数的后面,否则会被重写
}
var s1=new student("dxy");
s1.say();//会报错,Uncaught TypeError: s1.say is not a function,无法继承父对象的方法
组合式继承:
function student(age,name){
person.call(this,name);
this.age=age;
}
student.prototype=new person();
es6的继承:
class Animal {
//构造函数
constructor(props) {
this.name = props.name || '未知';
}
eat() {
alert(this.name + "在吃东西...");
}
}
//class继承
class Bird extends Animal {
//构造函数
constructor(props) {
//调用实现父类的构造函数
super(props);
this.type = props.type || "未知";
}
fly() {
alert(this.name + "在飞...");
}
}
var myBird = new Bird({
name: '鹦鹉'
})
myBird.eat()
myBird.fly()
//构造函数
constructor(props) {
this.name = props.name || '未知';
}
eat() {
alert(this.name + "在吃东西...");
}
}
//class继承
class Bird extends Animal {
//构造函数
constructor(props) {
//调用实现父类的构造函数
super(props);
this.type = props.type || "未知";
}
fly() {
alert(this.name + "在飞...");
}
}
var myBird = new Bird({
name: '鹦鹉'
})
myBird.eat()
myBird.fly()