图解call、apply、bind的异同及各种实战应用演示

hafe 8年前

来自: http://www.cnblogs.com/shuiyi/p/5178742.html

一、图解call、apply、bind的异同

JavaScript中函数可以通过3种方法改变自己的this指向,它们是call、apply、bind。它们3个非常相似,但是也有区别。下面表格可以很直观看出三者的不同

方法 是否直接执行函数 传入的参数 调用方式
call

(context,arg1,arg2,arg3...)

第二个参数之后都是实参

function.call(context,arg1,arg2,arg3...)

apply

(context,[arg1,arg2,arg3...])

第二个参数必须是数组

function.apply(context,[arg1,arg2,arg3...])

bind

(context)

只有一个参数

var newFunction = function.bind(context);

newFunction(arg1,arg2,arg3...)

二、实例:

1、call

    var a = {x: 1};      var b = function (y, z) {          console.log(this.x + y + z)      };      b.call(a, 3, 4);//此时b的this(即b执行时的上下文)被改变为a,因此this.x为1,第二个参数之后都是传给b实参。

2、apply

   var a = {x: 1};      var b = function (arr) {          console.log(this.x + arr[0] + arr[1])      };      b.call(a, [3, 4]);//此时b的this(即b执行时的上下文)被改变为a,第二个参数是一个数组

3、bind

    var a = {x: 1};      var b = function (y, z) {          console.log(this.x + y + z)      };      var newB = b.bind(a);//此时b的this(即b执行时的上下文)被改变为a,由此生成一个新函数,函数不会立即执行。      newB(3, 4);//函数此时才执行

三、常用场景

1、数组之间追加

     var array1 = [12, "foo", {name: "Joe"}, -2458];      var array2 = ["Doe", 555, 100];      Array.prototype.push.apply(array1, array2);      /* array1 值变为  [12 , "foo" , {name:"Joe"} , -2458 , "Doe" , 555 , 100] */    View Code

2、获取数组中的最大值和最小值

     var numbers = [5, 458, 120, -215];      var maxInNumbers = Math.max.apply(Math, numbers);  //458    View Code

3、验证是否是数组(前提是toString()方法没有被重写过)

     function isArray(obj){          return Object.prototype.toString.call(obj) === '[object Array]';      }    View Code

4、类(伪)数组使用数组方法

 var domNodes = Array.prototype.slice.call(document.getElementsByTagName("*"));    View Code

5、数字求和

     function sum() {          var numberSum = Array.prototype.reduce.apply(arguments, [function (prev, next) {              return prev + next;          }]);          console.log(numberSum);      }      sum(1, 2, 3);    View Code

备注:以上1-4的使用场景来自,有兴趣的同学可以前往了解更多: https://github.com/chokcoco/apply-call-bind/tree/master