apply、call 、bind做用和区别

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

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

apply、call的做用

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

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方法:java

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()方法。react

当一个对象没有某个方法,可是其余对象的有,咱们能够借助call或apply用其它对象的方法来操做。git

apply、call的区别

apply、call做用彻底同样,只是接受参数的方式不太同样。例如:github

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

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

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

经常使用方法:dom

  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…

相关文章
相关标签/搜索