JS中,Function的原型拥有三个功能很相近的方法,分别是call,apply,bind。它们的功能都是向调用它们的Function传入this,和argments,但是又有小差异。
1、Function.prototype.call:
(1)参数:接受一系列参数,你想将函数内this重新赋值的thisValue,函数接受的参数列表args。
(2)反馈机制:向调用call的Function传入参数后,以传入的参数,执行调用call的函数。
function print (a, b) { this.a = a; this.b = b; console.log(this.a, this.b); } // 在控制台输出 3, 4 print(3, 4) // 在控制台输出 3, 4 var obj = {
b: 4
} print.call(obj, 3)
2、Function.prototype.apply:
(1)参数:接受两个参数,第一个是将要改变this的thisValue,一个是参数数组。
(2)反馈机制:向调用apply的Function传入参数后,以传入的参数,执行调用apply的函数。
function print (a, b) { this.a = a; this.b = b; console.log(this.a, this.b); } // 在控制台输出 3, 4 print(3, 4) // 在控制台输出 3, 4 var obj = {} print.apply(obj, [3, 4])
3、Function.prototype.bind:
(1)参数:接受两个参数,第一个是将要改变的this的thisValue,一个是参数列表。
(2)反馈机制:向调用bind的Function传入参数后,返回改变上下文中的this后的调用bind的函数引用。
function print (a, b) { this.a = a; this.b = b; console.log(this.a, this.b); } var obj = {} var p = print.bind(obj, 3, 4) // 在控制台输出 3, 4 p()