继承-js

1、 call apply bind的区别

相同点:
1:改变this的指向;
2:可用来实现继承
3:第一个参数都是this要指向的对象
不同点:
1:call和bind可以传很多参数,apply第二个参数必须是数组;
2: call,apply是立即执行,bind是需要调用才执行;

call() 的用法
    function Father(eat){
   		this.eat=eat
		this.footEat=function(){
			console.log('超能吃'+this.eat)
		}
	}
	function Children(foot){
   		Father.call(this,foot)
	}
	var son= new Children('肉')
	son.footEat() // 超能吃肉
apply() 用法
  function Father(eat1,eat2){
   		this.eat1=eat1
   		this.eat2=eat2
		this.footEat=function(){
			console.log('超能吃'+this.eat1+','+this.eat2)
		}
	}
	function Children(foot){
   		Father.apply(this,foot)
   		//如果传字符串就会报错
   		// Fater.apply(this,'蔬菜')   error
	}
	var son= new Children(['蔬菜','冰激凌'])
	son.footEat() // 超能吃蔬菜,冰激凌
bind() 用法
  function Father(eat){
   		this.eat=eat
		this.footEat=function(){
			console.log('超能吃'+this.eat)
		}
	}
	function Children(foot){
		//bind需要调用一下才能执行
   		Father.bind(this,foot)()
	}
	var son= new Children('水果')
	son.footEat() // 超能吃水果
实现继承的几种方式
(1)利用call 、apply 和bind实现继承

例子如上文 :优点简单明了,缺点无法继承原型链上的属性跟方法

(2)原型链继承

利用原型链来实现继承,父类的实例作为子类的原型,(子.prototype=new 父())
缺点:1.当原型链中包含引用类型值的原型时,该引用类型值会被所有实例共享。
2.在创建子类型时,不能向超类进行传参

(3)组合继承

利用原型继承和借用构造函数继承实现的一种继承。

(4)ES6的extends继承
class Father {
  constructor (name){
	this.name=name
}
showName(){
console.log(this.name)
 }
}

class Son extends  Father {
  constructor (name){
	super(name)
	this.type='姓名'
}
}
var son = new Son ('小明')
son.showName()  // 小明
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值