简单的来说,apply、call和bind这三个函数都是用来改变this指向,也就是上下文。但是用法稍有不同。

小红书上的定义:

apply函数接收两个参数,一个是在其中运行函数的作用域,另一个是参数数组,其中第二个参数可以是Array的实例,也可以是arguments对象。

对于call()方法而言,第一个参数是this 值没有变化,变化的是其余参数都直接传递给函数。换句话说,在使用call()方法时,传递给函数的参数必须逐个列举出来。

bind这个方法会创建一个函数的实例,其this 值会被绑定到传给bind()函数的值。

应用场景:

1、数组之间的运算

 1.1 数组追加

var array1 = [1, 2, 3];

var array2 = [4, 5, 6];

Array.prototype.push.apply(array1, array2);

 1.2 获取数组中的最大和最小值

var numbers = [1, 2, 3, 4, 5];

var max = Math.max.apply(Math, numbers);

2、类数组使用数组方法

常见类数组有arguments对象,还有像调用getElementsByClassName,document.childNodes之类的,它们返回的NodeList对象都属于伪数组。

var domNodes = Array.prototype.slice.call(document.getElementsByClassName("test"))

3、判断类型

console.log(Object.prototype.toString.call(123)) //[object Number]
console.log(Object.prototype.toString.call('123')) //[object String]
console.log(Object.prototype.toString.call(undefined)) //[object Undefined]
console.log(Object.prototype.toString.call(true)) //[object Boolean]
console.log(Object.prototype.toString.call({})) //[object Object]
console.log(Object.prototype.toString.call([])) //[object Array]
console.log(Object.prototype.toString.call(function(){})) //[object Function]
4. 实现继承
function Animal(name){  
  this.name = name;  
  this.showName = function(){  
    console.log(this.name);  
  }  
}  
function Cat(name){ 
  Animal.call(this, name); 
}
var cat = new Cat("Black Cat");  
cat.showName();

apply、call和bind三者比较

apply和call功能相同,只不过apply后面传入的参数数组,而call后面的参数是一个一个传入的。

var obj = {
x: 81,
};

var foo = {
getX: function() {
return this.x;
}
}

console.log(foo.getX.bind(obj)()); //81
console.log(foo.getX.call(obj)); //81
console.log(foo.getX.apply(obj)); //81

 上述代码可以看出,apply和call都是立即调用,而bind的返回对应函数,便于稍后调用。

posted on 2018-03-27 17:03  小马落落  阅读(246)  评论(0编辑  收藏  举报