call,apply,bind三者的用法

116 阅读1分钟

call、apply、bind都是改变this指向的方法

1.call

当call方法执行的时候,会进行一下几步: 1.首先把要操作的函数中的this关键字变为call方法第一个传递的实参 2.把call方法第二个及之后的实参获取到传递给函数

非严格模式 如果不传参,或者第一个参数是this、undefind或null,this都是指向window

    let key=function(a,b){
        console.log(this,a,b);
    }
    let sleep={ name:'猪八戒'};
    key.call(this) //this:window,a:undefind,b:undefind
    key.call(1,2)  //this:1,a:2,b:undefind
    key.call(this,1,2) //this:window,a:1,b:2
    key.call() //this:window,a:undefind,b:undefind
    key.call(sleep) //this:sleep,a:undefind,b:undefind
    key.call(null) //this:window,a:undefind,b:undefind
    key.call(undefined) //this:window,a:undefind,b:undefind

严格模式 第一个参数是谁,this就指向谁,包括null和undefined,如果不传参数this就是undefined

    'use strict'
    function key(a,b){
        console.log(this,a,b);
    }
    let sleep={ name:'猪八戒'};
    key.call(this) //this:window,a:undefind,b:undefind
    key.call(1,2)  //this:1,a:2,b:undefind
    key.call(this,1,2) //this:window,a:1,b:2
    key.call() //this:undefind,a:undefind,b:undefind
    key.call(sleep) //this:sleep,a:undefind,b:undefind
    key.call(null) //this:null,a:undefind,b:undefind
    key.call(undefined) //this:undefind,a:undefind,b:undefind

2.apply

apply的方法和call方法执行基本一致,只不过传参方式不太一样,需把想要传递给函数的参数用数组整合起来。

   key.call(this,1,2) //this:window,a:1,b:2
   key.apply(this,[1,2]) //this:window,a:1,b:2

3.bind

bind的方法和call方法执行基本一致,区别在于立即执行还是等待执行

key.call(sleep,1,2) //改变key中的this,并且key立即执行
    key.bind(sleep,1,2) //改变key中的this,key并不执行