likes
comments
collection
share

JavaScript 第一章 bind、call、apply 的基本概念

作者站长头像
站长
· 阅读数 23
  • call apply bind 作用是改变函数执行时的上下文,简而言之就是改变函数运行时的this指向。
  • call 传入参数列表,apply 传入数组,但是都会立即执行。
  • bind 传入参数列表,不会立即执行,适合在定时器等回调函数中使用。

    let fun = dog.eat.bind(cat,'fish');
    
    fun();

1、例子

  • 代码中可以看到,正常情况say方法输出martin
  • 但是我们把say放在setTimeout方法中,在定时器中是作为回调函数来执行的,因此回到主栈执行时是在全局执行上下文的环境中执行的,这时候this指向window,所以输出lucy

    const name="lucy";
    
    const obj={
        name:"martin",
        say:function () {
            console.log(this.name);
        }
    };
    
    obj.say(); //martin,this指向obj对象
    
    setTimeout(obj.say,0); //lucy,this指向window对象
  • 实际需要的是this指向obj对象,这时候就需要该改变this指向了。

    setTimeout(obj.say.bind(obj),0); //martin,this指向obj对象

2、区别

  • 三者都可以改变函数的this对象指向
  • 三者第一个参数都是this要指向的对象,如果如果没有这个参数或参数为undefinednull,则默认指向全局window
  • 三者都可以传参,但是apply是数组,而call是参数列表,且applycall是一次性传入参数,而bind可以分为多次传入
  • bind 是返回绑定this之后的函数,apply call 则是立即执行

1)apply 方法

  • apply接受两个参数,第一个参数是this的指向,第二个参数是函数接受的参数,以数组的形式传入。
  • 改变this指向后原函数会立即执行,且此方法只是临时改变this指向一次。

    function fn(...args){
        console.log(this,args);
    }
    
    let obj = {
        myname:"张三"
    }
    
    fn.apply(obj,[1,2]); // this会变成传入的obj,传入的参数必须是一个数组;
    
    fn(1,2) // this指向window
  • 当第一个参数为nullundefined的时候,默认指向window(在浏览器中) 。

    fn.apply(null,[1,2]); // this指向window
    
    fn.apply(undefined,[1,2]); // this指向window

2)call 方法

  • call方法的第一个参数也是this的指向,后面传入的是一个参数列表。
  • apply一样,改变this指向后原函数会立即执行,且此方法只是临时改变this指向一次。

    function fn(...args){
     console.log(this,args);
    }
    
    let obj = {
     myname:"张三"
    }
    
    fn.call(obj,1,2); // this会变成传入的obj
    
    fn(1,2) // this指向window
  • 同样的,当第一个参数为nullundefined的时候,默认指向window(在浏览器中) 。

    fn.call(null,[1,2]); // this指向window
    
    fn.call(undefined,[1,2]); // this指向window

3)bind 方法

  • bind方法的第一参数也是this的指向,后面传入的也是一个参数列表(但是这个参数列表可以分多次传入)。
  • 改变this指向后不会立即执行,而是返回一个永久改变this指向的函数。

    function fn(...args){
        console.log(this,args);
    }
    
    let obj = {
        myname:"张三"
    }
    
    const bindFn = fn.bind(obj); // this 也会变成传入的obj ,bind不是立即执行需要执行一次
    bindFn(1,2) // this指向obj
    
    fn(1,2) // this指向window

3、基于call的继承

  • 可以通过 call,子类可以使用父类的方法。

    function Animal(){
        this.eat = function(){
            log("eating...")
        }
    }
    
    function Cat(){
        Animal.call(this);
    }
    
    let cat = new Cat();
    
    cat.eat();

4、bind的实现

  • bind 的实现

    Function.prototype.myBind = function (context) {
        // 判断调用对象是否为函数
        if (typeof this !== "function") {
            throw new TypeError("Error");
        }
    
        // 获取参数
        const args = [...arguments].slice(1);
        
        fn = this;
    
        return function Fn() {
    
            // 根据调用方式,传入不同绑定值
            return fn.apply(this instanceof Fn ? new fn(...arguments) : context, args.concat(...arguments)); 
        }
    }