美文网首页
话说call,apply和bind

话说call,apply和bind

作者: Jason_Shu | 来源:发表于2018-10-06 14:55 被阅读0次

call,apply和bind都是用来改变函数的this对象的指向。首先说说他们的相同点:

  1. 都可以用来改变this对象的指向。
  2. 第一个参数必须是this要指向的对象。
  3. 都可以使用后面的参数进行传参。

我们来看看这段代码:

var bigBrother = {
    name: '哥哥',
    age: 24,
    sayName: function() {
        console.log(this.name)
    },
};


var littleBrother = {
    name: '弟弟',
    age: 22,
};

bigBrother.sayName.call(bigBrother);  // "哥哥"

bigBrother.sayName.apply(bigBrother);  // "哥哥"

bigBrother.sayName.bind(bigBrother)();  // "哥哥"

如果我们想把bigBrother里的sayName函数作用于littleBrother呢?

我们可以这样写:

bigBrother.sayName.call(littleBrother);  //  "弟弟"

bigBrother.sayName.apply(littleBrother);  //  "弟弟"

bigBrother.sayName.bind(littleBrother)();  //  "弟弟"

从上述代码我们可以看到前面还是「bigBrother.sayName」,调用bigBrother对象里面的sayName函数,只不过在后面把this对象指向了littleBrother,所以可以使littleBrother同样具有sayName函数的效果,输出“弟弟”。

在上述代码中,我们可以看到call和apply调用基本是一样的,两者都是对函数的直接调用,但是bind有些不同,bind返回一个函数,如果要执行的话后面要加上();

那call和apply有啥区别呢?我们再传点参数,如下代码:

var bigBrother = {
    name: '哥哥',
    age: 24,
    sayInfo: function(school, grade) {
        console.log(this.name, school, grade);
    },
};


bigBrother.sayInfo.call(bigBrother, "实验小学", "一年级");
bigBrother.sayInfo.apply(bigBrother, ["实验小学", "一年级"]);
bigBrother.sayInfo.bind(bigBrother, "实验小学", "一年级")();

从上面可以看出,call和apply第一个参数后的参数,call是分别罗列第二个和第三个参数,而apply是把第一个参数后所有的参数都放入一个数组中,作为第二个参数。

相关文章

网友评论

      本文标题:话说call,apply和bind

      本文链接:https://www.haomeiwen.com/subject/eethaftx.html