原型链、继承

目标

了解原型链和原型对象

js实现各种方式的继承


知识要点

constructor

构造器,当创建对象时会在原型中拥有一个constructor,constructor指向构造函数本身

原型链

js中所有皆为对象

对象中会有__proto__原型链属性,原型链指向构造函数中的prototype原型

函数中除了__proto__原型链属性,还会有prototype原型

function Foo(){}
var foo = new Foo()
foo.__proto__ === Foo.prototype; // true
Foo.prototype.constructor === Foo; // true
Foo.__proto__ === Function.prototype; // true
Function.__proto__ === Object.prototype; // true
Object.__proto__ === Function.prototype; // true
Object.prototype.__proto__ === null; //true
Foo.prototype.__proto__ === Object.prototype; // true

继承(各种继承方式的优缺点)

原型链继承

function Father() {
   this.name = 'father';
}
Father.prototype.say = function() {
   alert('father func')
}
function Child(){}
Child.prototype = new Father();
Child.prototype.constructor = Child;

缺点:

  1. 子类共享了父类的属性
  2. 实例化时无法向父类传参

构造函数继承

function Father() {
   this.name = 'father';
}
Father.prototype.say = function() {
   alert('father func')
}
function Child(){
   Father.apply(this, Array.from(arguments))
}

优点:

  1. 解决了属性共享的问题
  2. 可以给父类传参

缺点:

无法获取prototype方法

组合继承

function Father() {
   this.name = 'father';
}
Father.prototype.say = function() {
   alert('father func')
}
function Child() {
   Father.apply(this, Array.from(arguments))
}
Child.prototype = new Father();
Child.prototype.constructor = Child;

优点:

  1. 解决了属性共享的问题
  2. 可以给父类传参
  3. 可以获取prototype方法

缺点:

会调用两次构造函数

寄生组合继承

function Father() {
   this.name = 'father';
}
Father.prototype.say = function() {
   alert('father func')
}
function Child() {
   Father.apply(this, Array.from(arguments))
}
Child.prototype = Object.create(Father.prototype);
Child.prototype.constructor = Child;

优点:解决了以上问题

多重继承

function Father() {
   this.name = 'father';
}
Father.prototype.say = function() {
   alert('father func')
}
function Child() {
   Father.apply(this, Array.from(arguments))
}
function OtherChild() {
   this.name = 'otherChild';
}
OtherChild.prototype.getName = function() {
   return this.name;
}
Child.prototype = Object.create(Father.prototype);
Object.assign(Child.prototype, OtherChild.prototype);
Child.prototype.constructor = Child;

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值