继承 :子类继承父类
声明一个父类:属性和行为
声明一个子类对象
面向对象 有三大特征: 封装 继承 多态
1、原型链继承(核心: 将父类的实例作为子类的原型)
优点:非常纯粹的继承关系,实例是子类的实例,也是父类的实例
父类新增原型方法/原型属性,子类都能访问到,简单,易于实现
缺点:要想为子类新增属性和方法,必须要在new Animal()这样的语句之后执行,不能放到构造器中
无法实现多继承
创建子类实例时,无法向父类构造函数传参
function animal() {
this.name = null;
this.sex = null;
this.sleep = function () {
return this.name + "睡觉";
}
}
function cat() {
this.type = "猫科";
}
cat.prototype = new animal();
cat.prototype.color = "white";
var Cat = new cat();
console.log(Cat)
console.log(Cat instanceof cat);
console.log(Cat instanceof animal);
2、构造继承
call apply 对象指针的替换
区别: 传递的参数的方式不一样
call 有多个参数
apply 有两个参数
优点:创建子类实例时,可以向父类传递参数
可以实现多继承(call多个父类对象)
缺点:实例并不是父类的实例,只是子类的实例
只能继承父类的实例属性和方法,不能继承原型属性/方法
无法实现函数复用,每个子类都有父类实例函数的副本,影响性能
function animal1() {
this.color = arguments[0];
this.sleep = function () {
return this.name + "正在睡觉";
}
}
function animal2() {
this.name = arguments[0];
this.sex = arguments[1];
this.eat = function () {
return this.name + "正在吃饭";
}
}
function dog(name, sex, color) {
this.type = "犬科";
animal1.call(this, color);
animal2.apply(this, [name, sex]);
}
var Dog = new dog("张三", "男", "黑色");
console.log(Dog);
console.log(Dog.sleep());
console.log(Dog.eat());
console.log(Dog instanceof dog);
console.log(Dog instanceof animal1);
console.log(Dog instanceof animal2);
3、实例继承
new对象返回对象
优点:不限制调用方式,不管是new 子类()还是子类(),返回的对象具有相同的效果
缺点:实例是父类的实例,不是子类的实例
不支持多继承
function animal3(){
this.name=null;
this.run=function(){
return this.name+"正在跑步";
}
}
function f1(){
var f1=new animal3();
return f1;
}
var ff=new f1( );
console.log(ff);
console.log(ff.run());
4、组合继承 去弥补原型链继承和构造继承的缺点
function Mutou() {
this.name = arguments[0];
this.make = function () {
return "制作" + this.name;
}
}
function Bandeng(name) {
Mutou.call(this, name);
}
Bandeng.prototype = new Mutou();
var ban = new Bandeng("板凳");
console.log(ban);
console.log(ban.make());
console.log(ban instanceof Bandeng);
console.log(ban instanceof Mutou);