call()
语法:call(thisArg,arg1,arg2,....)
定义:调用一个对象的一个方法,以另一个对象替换当前对象。
说明: call 方法可以用来代替另一个对象调用一个方法。call 方法可将一个函数的对象上下文从初始的上下文改变为由 thisObj 指定的新对象。 如果没有提供 thisObj 参数,那么 Global 对象被用作 thisObj。
function Func1(x,y) {
this.sum = x + y;
}
function Fun2(x,y) {
Func1.call(this, x, y);
}
let aNumber = new Fun2(1,2)
console.log(aNumber.sum) // 3
apply()
语法:apply(thisArg, [arg1,arg2,....])
定义:应用某一对象的一个方法,用另一个对象替换当前对象。
说明: 如果 argArray 不是一个有效的数组或者不是 arguments 对象,那么将导致一个 TypeError。 如果没有提供 argArray 和 thisObj 任何一个参数,那么 Global 对象将被用作 thisObj, 并且无法被传递任何参数。
function Func1(x,y) {
this.sum = x + y;
}
function Fun2(x,y) {
Func1.apply(this, [x, y]);
}
let aNumber = new Fun2(1,2)
console.log(aNumber.sum) // 3
这两者的区别就是call()接收若干个参数的列表,apply()接收一个包含多个参数的数组
bind()
语法:bind(thisArg, [arg1,arg2,....])
定义:bind() 方法为被选元素添加一个或多个事件处理程序,并规定事件发生时运行的函数。
说明:bind() 方法创建一个新的函数,在 bind() 被调用时,这个新函数的 this 被指定为 bind() 的第一个参数,而其余参数将作为新函数的参数,供调用时使用。
this.x = 9; // 在浏览器中,this 指向全局的 "window" 对象
var module = {
x: 81,
getX: function() { return this.x; }
};
module.getX(); // 81
var retrieveX = module.getX;
retrieveX();
// 返回 9 因为函数是在全局作用域中调用的
// 创建一个新函数,把 'this' 绑定到 module 对象
// 新手可能会将全局变量 x 与 module 的属性 x 混淆
var boundGetX = retrieveX.bind(module);
boundGetX(); // 81
bind() 最简单的用法是创建一个函数,不论怎么调用,这个函数都有同样的 this 值。