call,apply,bind

call

非严格模式

        var obj = { name: "jie" };
        function fn(num1, num2) {
            console.log(this);
            console.log(num1 + num2);
        }
        fn(100,200);   //this ->window  num1=100,num2=200
        fn.call(100,200)   //this->100  num1 = 200,num2=undefined
        fn.call(obj,100,200);  //this->obj  num1 = 100,num2=200

        fn.call();  //this->window
        fn.call(null); //this->window
        fn.call(undefined); //this->window

严格模式

        'use strict';
        var obj = {name:"jie"};
        function fn(num1,num2){
            console.log(this);
            console.log(num1+num2);
        }
        fn(100,200);   //this ->window  num1=100,num2=200
        fn.call(100,200)   //this->100  num1 = 200,num2=undefined
        fn.call(obj,100,200);  //this->obj  num1 = 100,num2=200

        fn.call();   //undefined
        fn.call(null);  //null
        fn.call(undefined);  //undefined

apply

  1. apply和call的方法的作用是一模一样的,
  2. call在给fn传递参数的时候,是一个个的传递值的,而apply不是一个一个传,而是把要给fn传递的参数值统一放在一个数组中进行操作,但是也相当于一个个的给fn的形参赋值
        var obj = { name: "jie" };
        function fn(num1, num2) {
            console.log(this);
            console.log(num1 + num2);
        }
        fn(100,200);   //this ->window  num1=100,num2=200
        fn.apply([100,200])   //this->[100,200]  num1 = NaN,num2=NaN
        fn.apply(obj,[100,200]);  //this->obj  num1 = 100,num2=200

        fn.apply();  //this->window
        fn.apply(null); //this->window
        fn.apply(undefined); //this->window

bind

  1. 预处理:事先把fn的this改变为我们想要的结果,并且把对应的参数值也准备好,以后要用到了,直接的执行即可
  2. var result = fn.bind(obj,1,2) 只是改变了fn中的this为obj,并且给fn传递了两个参数值100,200,但是此时并没有把fn这个函数执行,执行bind会有一个返回值,这个返回值result就是我们把fn的this改变后的哪个结果
        var obj = { name: "jie" };
        function fn(num1, num2) {
            console.log(this);
            console.log(num1 + num2);
        }
        var result = fn.bind(obj, 100, 200);  //this->obj  num1 = 100,num2=200
        console.log(result)

原文地址:https://www.cnblogs.com/lalalagq/p/9898407.html