apply、call 、bind作用和区别

5,870 阅读4分钟

apply、call 、bind有什么作用?什么区别?

JavaScript 的一大特点是,函数存在「定义时上下文」和「运行时上下文」以及「上下文是可以改变的」这样的概念。

apply、call的作用

call和apply都是为了改变某个函数运行时的上下文(context)而存在的,换句话说,就是为了改变函数体内部this的指向。例如:

function fruits() {}

fruits.prototype = {
    color: "red",
    say: function () {
        console.log("My color is " + this.color);
    }
};

var apple = new fruits;
apple.say();    //My color is red

但是如果我们有一个对象banana= {color : 'yellow'} ,我们不想对它重新定义say方法,那么我们可以通过使用call或apply方法:

banana = {
    color: 'yellow'
};
apple.say.call(banana); //My color is yellow
apple.say.apply(banana); //My color is yellow

call、apply动态改变this执行上下文为传入的参数banana,使得banana具有了say()方法。

当一个对象没有某个方法,但是其他对象的有,我们可以借助call或apply用其它对象的方法来操作。

apply、call的区别

apply、call作用完全一样,只是接受参数的方式不太一样。例如:

var func = function(arg1, arg2) {};
func.call(this, arg1, arg2);
func.apply(this, [arg1, arg2]);

其中 this 是你想指定的上下文。 call需要把参数按顺序传递进去,而apply则是把参数放在数组里再传进去。

当函数参数是明确知道数量时建议用call 当函数参数数量不固定时建议用apply,然后把参数push进数组传递进去。

常用方法:

  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]
  1. 获取数组中的最大值和最小值
var numbers = [5, 458 , 120 , -215 ];
var maxInNumbers = Math.max.apply(Math, numbers),   //458
    maxInNumbers = Math.max.call(Math,5, 458 , 120 , -215); //458
  1. 类数组使用数组方法
var domNodes = Array.prototype.slice.call(document.getElementsByTagName("*"));
// 使getElementsByTagName()方法返回的类数组具有数组的方法

bind作用

bind()方法会创建一个新函数,称为绑定函数,当调用这个绑定函数时,绑定函数会以创建它时传入bind()方法的第一个参数作为this,传入bind()方法的第二个以及以后的参数加上绑定函数运行时本身的参数按照顺序作为原函数的参数来调用原函数。

示例如下:

// 使用_this等保存this ,以便在改变了上下文之后继续引用到它
var foo = {
  bar : 1,
  eventBind: function () {
    var _this = this;
    $('.someClass').on('click',function (event) {
      /* Act on the event */
      console.log(_this.bar);
    });
  }
}
// 使用bind()方法创建了一个新函数,当这个click事件绑定在被调用的时候,this指向调用bind()时传入的第一个参数(即foo对象)。
var foo = {
  bar : 1,
  eventBind: function () {
    $('.someClass').on('click',function (event) {
      /* Act on the event */
      console.log(this.bar);
    }.bind(this));
  }
}

apply、call、bind比较

示例如下:

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

三个输出的都是81,但是注意看使用 bind() 方法的,他后面多了对括号。当你希望改变上下文环境之后并非立即执行,而是回调执行的时候,使用 bind() 方法。而 apply/call 则会立即执行函数。

总结:

  • apply、call、bind三者都是用来改变函数的this的指向的;
  • apply、call、bind三者第一个参数都是this要指向的调用对象,也就是想指定的上下文;
  • apply、call、bind三者都可以利用后续参数传参;
  • bind是返回对应函数,便于稍后调用;apply 、call则是立即调用。

下面代码输出什么?为什么?

var john = {
  firstName: "John"
};
function func() {
  alert(this.firstName + ": hi!")
}
john.sayHi = func; // this指向当前执行上下文john
john.sayHi();
// 输出:John: hi!

下面代码输出什么?为什么?

func(); // this指向当前执行上下文window
function func() {
  alert(this);
}
// 输出:window

下面代码输出什么?为什么??

document.addEventListener('click', function(e){
    console.log(this); // this指向当前执行上下文document
    setTimeout(function(){
        console.log(this); // this指向当前执行上下文window
    }, 200);
}, false);
// 输出:document  window

下面代码输出什么?为什么?

var john = {
  firstName: "John"
}

function func() {
  alert(this.firstName); // this指向当前执行上下文window
}
func.call(john); // call函数改变函数func()的执行上下文为call()的第一个参数,即john,因此this指向执行上下文john
// 输出:John

以下代码有什么问题?如何修改?

// 修改前
var module= {
  bind: function () {
    $btn.on('click', function () {
      console.log(this); //this指向当前执行上下文$btn
      this.showMsg(); // 当前执行上下文$btn没有showMsg()方法,无法调用
    });
  },

  showMsg: function () {
    console.log('饿了么');
  }
};

// 修改后
var module= {
  bind: function () {
    const _this = this; //将this指向的当前执行上下文module保存为_this
    $btn.on('click', function () {
      console.log(this); //this指向当前执行上下文$btn
      _this.showMsg(); // _this即module,可以调用showMsg()方法
    });
  },

  showMsg: function () {
    console.log('饿了么');
  }
};

另外最近正在写一个编译 Vue 代码到 React 代码的转换器,欢迎大家查阅。

github.com/mcuking/vue…