Javascript 实现继承的几种方式

面向对象的基本特征有:封装、继承、多态。

在JavaScript中实现继承的方法:

  1. 原型链(prototype chaining)

  2. 构造继承:call()/apply()

  3. 混合继承(prototype和call()/apply()结合)

  4. 对象冒充

1、原型链继承

核心: 将父类的实例作为子类的原型

缺点: 父类新增原型方法/原型属性,子类都能访问到,父类一变其它的都变了。

function teacher(name){
    this.name = name;
}
teacher.prototype.sayName = function(){
    console.log("name is "+this.name);
}
var teacher1 = new teacher("xiaoming");
teacher1.sayName();
 
function student(name){
    this.name = name;
}
student.prototype = new teacher()
var student1 = new student("xiaolan");
student1.sayName();
//  name is xiaoming
//  name is xiaolan

2. 构造继承:call()/apply()

基本思想:
借用构造函数的基本思想就是利用call或者apply把父类中通过this指定的属性和方法复制(借用)到子类创建的实例中。
因为this对象是在运行时基于函数的执行环境绑定的。也就是说,在全局中,this等于window,而当函数被作为某个对象的方法调用时,this等于那个对象。
call、apply 方法可将一个函数的对象上下文从初始的上下文改变为由 thisObj 指定的新对象。

核心:使用父类的构造函数来增强子类实例,等于是复制父类的实例属性给子类(没用到原型)

缺点: 方法都在构造函数中定义, 只能继承父类的实例属性和方法,不能继承原型属性/方法,无法实现函数复用,每个子类都有父类实例函数的副本,影响性能

扫描二维码关注公众号,回复: 3570956 查看本文章
function teacher(name,age){
this.name = name;
this.age = age;
this.sayhi = function(){
alert('name:'+name+", age:"+age);
}
}
function student(){
var args = arguments;
teacher.call(this,args[0],args[1]);
// teacher.apply(this,arguments);
}
var teacher1 = new teacher('xiaoming',23);
teacher1.sayhi();

var student1 = new student('xiaolan',12);
student1.sayhi();

// alert: name:xiaoming, age:23
// alert: name:xiaolan, age:12

3. 混合继承(prototype和call()/apply()结合)

组合继承(所有的实例都能拥有自己的属性,并且可以使用相同的方法,组合继承避免了原型链和借用构造函数的缺陷,结合了两个的优点,是最常用的继承方式)

核心:通过调用父类构造,继承父类的属性并保留传参的优点,然后再通过将父类实例作为子类原型,实现函数复用

缺点:调用了两次父类构造函数,生成了两份实例(子类实例将子类原型上的那份屏蔽了)

function teacher(name,age){
this.name = name;
this.age = age;
}
teacher.prototype.sayName = function(){
console.log('name:'+this.name);
}
teacher.prototype.sayAge = function(){
console.log('age:'+this.age);
}

function student(){
var args = arguments;
teacher.call(this,args[0],args[1]);
}
student.prototype = new teacher();

var student1 = new student('xiaolin',23);
student1.sayName();
student1.sayAge();
// name:xiaolin
// age:23

4、对象冒充

function Person(name,age){
this.name = name;
this.age = age;
this.show = function(){
console.log(this.name+", "+this.age);
}
}

function Student(name,age){
this.student = Person; //将Person类的构造函数赋值给this.student
this.student(name,age); //js中实际上是通过对象冒充来实现继承的
delete this.student; //移除对Person的引用
}

var s = new Student("小明",17);
s.show();

var p = new Person("小花",18);
p.show();
// 小明, 17
// 小花, 18

猜你喜欢

转载自blog.csdn.net/baidu_30668495/article/details/83040449