apply()、call()、bind()调用对象的一个方法,用另一个对象代替当前对象;改变函数执行的上下文,换句话说就是改变函数体内部的this的指向,实现(多重)继承
区别:
bind()是返回的是执行上下文被改变的函数且不会立即执行,call()、apply()直接执行该函数;
call()的传参是 call(this,param1,param2…),参数必须直接传给函数
apply()的传参是 apply(this,[argArray]);
bind()的传参是bind(this,param1,param2…);
第一个参数是指定的对象,这个对象就是该函数的执行上下文
call()和apply()如果第一个参数是null或者undefine那么this的指向就是全局变量,在浏览器里就是window对象
代码示例;
// apply()
let obj = {};
// 不需要参数的情况
function test() {
console.log(this === window);
console.log(this === obj);
}
test(); // true false
test.apply(obj); //false true
// 需要传参的
let obj = {
name: '飞哥'
};
function test(name) {
this.name = name;
console.log(window.name);
console.log(obj.name);
}
test("高飞"); // 高飞 飞哥
test.apply(obj, ['高飞']); // 高飞 高飞
// call()
// 不需要参数的情况
let obj = {};
function test() {
console.log(this === window);
console.log(this === obj);
}
test(); // true false
test.apply(obj); //false true
// 需要传参的
let obj = {
name: '飞哥'
};
function test(name) {
this.name = name;
console.log(window.name);
console.log(obj.name);
}
test("高飞"); // 高飞 飞哥
test.call(obj, '高飞'); // 高飞 高飞
// bind()
// 不需要参数的情况
let obj = {};
function test() {
console.log(this === window);
console.log(this === obj);
}
test(); // true false
test.bind(obj)(); //false true
// 需要传参的
let obj = {
name: '飞哥'
};
function test(name) {
this.name = name;
console.log(window.name);
console.log(obj.name);
}
test("高飞"); // 高飞 飞哥
test.bind(obj, '高飞')(); // 高飞 高飞