解释:js继承就是当设置一个父类方法时,子类可以不用再另外设置与父类相同的属性,而是直接继承父类的属性。
作用:做面向对象的开发以及框架库的封装。
一、定义父类:
// 定义一个动物类
function Animal (name) {
// 属性
this.name = name || 'Animal';
// 实例方法
this.sleep = function(){
console.log(this.name + '正在睡觉!');
}
}
二、方法
1.原型链继承
function Animal(){
}
function Cat(){
this.eat=function(){
return"fish";
}
this.sleep=function(){
return"睡觉";
}
}
Cat.prototype = new Animal();
Cat.prototype.name = 'cat';
var cat = new Cat();
console.log(cat.name);
console.log(cat.eat('fish'));
console.log(cat.sleep());
console.log(cat instanceof Animal);
console.log(cat instanceof Cat);
核心: 将父类的实例作为子类的原型
特点:
——非常纯粹的继承关系,实例是子类的实例,也是父类的实例
——父类新增原型方法/原型属性,子类都能访问到
——简单,易于实现
缺点:
要想为子类新增属性和方法,必须要在new Animal()这样的语句之后执行,不能放到构造器中无法实现多继承
创建子类实例时,无法向父类构造函数传参。
2.构造继承
function People() {
this.name = arguments[0];
this.sex = arguments[1];
this.eat = function () {
return this.name + "正在吃饭!";
}
}
function Student() {
this.score = arguments[0];
this.writezuoye = function () {
return this.name + "写作业";
}
}
//构造继承不能继承父类的原型方法和属性
Student.prototype.work = function () {
return this.name + "跑步";
}
function smallchildren(name, sex, score) {
/* People.call(this,name,sex);*/
People.apply(this, [name, sex]);
Student.call(this, score);
}
var small = new smallchildren("笑笑", "女", 487);
console.log(small instanceof People);//false
console.log(small instanceof smallchildren);//true
console.log(small);
console.log(small.eat());
console.log(small.writezuoye());
核心:使用父类的构造函数来增强子类实例,等于是复制父类的实例属性给子类。
特点:
——创建子类实例时,可以向父类传递参数
——可以实现多继承(call多个父类对象)
缺点:
——实例并不是父类的实例,只是子类的实例
——只能继承父类的实例属性和方法,不能继承原型属性/方法
——无法实现函数复用,每个子类都有父类实例函数的副本,影响性能
3.实例继承
function f1() {
this.name = null;
this.sleep = function () {
return "睡觉";
}
}
function f2() {
var f = new f1();
return f;
}
var fchild = new f2();
console.log(fchild);
console.log(fchild instanceof f2);//false
console.log(fchild instanceof f1);//true
var ff = f2();
特点:
——不限制调用方式,不管是new 子类()还是子类(),返回的对象具有相同的效果
缺点:
——实例是父类的实例,不是子类的实例
——不支持多继承
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);
特点:
——弥补了方法2 的缺点。
缺点:
——生成了两个实例,消耗内存。