js中的apply()、call() 和 bind()

apply()call(),这两个方法的用途都是在特定的作用域中调用函数,等同于设置函数体内部 this 指向的对象,也就是改变函数运行时的作用域。
  apply() 接收两个参数,第一个参数是给绑定 this 的值,第二个参数是参数数组,call() apply() 的作用相同,接收的第一个参数也相同,区别在于之后传入参数的方式不同,看个例子:

var o = {
  color: 'blue'
}
var color = "red";

function sayColor(num) {
  console.log(this.color + '-' + num);
};
sayColor(1); //red-1
sayColor.apply(o,[2]); //blue-2
sayColor.call(o,3); //blue-3

  可以看出,apply() call() 作用相同,传入参数也类似,区别只是apply() 传入的是个数组,call() 参数必须逐个列举出来传入。
  再说bind() ,传参方式和call() 比较相似,bind() 第一个参数也是绑定this的值,后面的参数也是需要逐个列举出来传入,不同的是,bind() 不会立即执行,bind() 会生成一个新的函数,之后就可以随时调用。说的不明白,看代码:

var o = {
  color: 'blue'
}
var color = "red";

function sayColor(num) {
  console.log(this.color + '-' + num);
};
var color = sayColor.bind(o,4);
color(); //blue-4

  bind() 并不支持IE6~8,若想要低版本的IE支持bind() ,需要通过Function prototype进行扩展,自定义一个bind() 方法。像这样:

if (! function() {}.bind) {
  Function.prototype.bind = function(context) {
    var self = this,
        args = Array.prototype.slice.call(arguments);
    return function() {
      return self.apply(context, args.slice(1));
    }
  };
}