JS对于原型继承和类式继承的 总结

转自https://www.cnblogs.com/constantince/p/4754992.html

  • 类式继承(构造函数)

类式继承是在函数对象内调用父类的构造函数,使得自身获得父类的方法和属性。call和apply方法为类式继承提供了支持。通过改变this的作用环境,使得子类本身具有父类的各种属性。

var father = function() {
  this.age = 52;
  this.say = function() {
    alert('hello i am '+ this.name ' and i am '+this.age + 'years old');
  }
}
 
var child = function() {
  this.name = 'bill';
  father.call(this);
}
 
var man = new child();
man.say();
  • 原型继承

我们说的原型继承,就是将父对像的方法给子类的原型

var father = function() {
}
father.prototype.a = function() {
}
var child = function(){}
//开始继承
child.prototype = new father();
var man = new child();
man.a();

组合模式
用类式继承属性,而原型继承方法
属性继承:(需要用 call 修改 this 指向)调用父类的构造函数
方法继承:子类要继承的构造函数名.prototype=new 父类构造函数名();

function father() {
  this.a = 'father'  
}
 
father.prototype.b = function() {
   alert(this.a)
}
 
var child = function() {
  father.call(this)
}
 
child.prototype = new father();
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值