call, apply, bind

主要目的都是为了 更改this 上下文, 实现继承,

call
  • function.call (x, 'value')
  • x为要把 funthis 重新定向的目标, 一般用的最多的都是对象 或者方法函数
  • value, 传值的方法是字符串
//对象
function func() {console.log(this)}
func()
// 可见this 指向的是window
// Window {stop: ƒ, open: ƒ, alert: ƒ, confirm: ƒ, prompt: ƒ, …}

//使用 call 更改其this指向的上下文为一个对象
var obj = {a: 1};
func.call(obj)
// {a: 1}

//方法

function Animal(){    
    this.name = "Animal";    
    this.showName = function(){    
        alert(this.name);    
    }    
}    
  
function Cat(){    
    this.name = "Cat";    
}    
   
var animal = new Animal();    
var cat = new Cat();    
    
//通过call或apply方法,将原本属于Animal对象的showName()方法交给对象cat来使用了。    
//输入结果为"Cat"    
animal.showName.call(cat,",");    
//animal.showName.apply(cat,[]); 
apply
  • function.apply(x, ['value'])
  • x为要把 funthis 重新定向的目标, 一般用的最多的都是对象 或者方法函数
  • value, 传值的方法是数组
//对象
function func() {console.log(this)}
func()
// 可见this 指向的是window
// Window {stop: ƒ, open: ƒ, alert: ƒ, confirm: ƒ, prompt: ƒ, …}

//使用 apply更改其this指向的上下文为一个对象
var obj = {a: 1};
func.apply(obj)
// {a: 1}

//方法

function Animal(){    
    this.name = "Animal";    
    this.showName = function(){    
        alert(this.name);    
    }    
}    
  
function Cat(){    
    this.name = "Cat";    
}    
   
var animal = new Animal();    
var cat = new Cat();    
    
//通过call或apply方法,将原本属于Animal对象的showName()方法交给对象cat来使用了。    
//输入结果为"Cat"       
animal.showName.apply(cat,[]); 
bind
  • bind通常用来重新绑定函数体中的 this 并放回一个具有指定 this的函数,多次 bind 是无效的。

  • callapply 则表示重新指定 this 并调用返回结果,区别在于 call采用多个实参的方式传参,apply 则是使用一个数组。

  • 共同点:第一个参数指定为 this,第二个参数起为参数传递。

  • 不同点:bind 是用来返回具有特定 this 的函数callapply 都是改变上下文中的 this立即执行这个函数

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容