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() // 小明