改变this指向的三种方法: call()方法、apply()方法、bind()方法
call()方法
1、可以进行函数的调用
2、可以改变this的指向,没有参数this指向window
3、可以改变this的指向,如果有一个参数,this指向当前参数
4、可以改变this的指向,如果有多个参数,this指向第一个参数,剩下的参数是参数列表
function fn() {
console.log('fn');
}
// fn()
fn.call()
var name = '全局的'
var obj_1 = {
name: 'obj_1',
getName: function (x, y, z) {
console.log(x, y, z);
console.log(this);
console.log(this.name);
}
}
// obj_1.getName()
obj_1.getName.call()
var obj_2 = {
name: 'obj_2'
}
obj_1.getName.call(obj_2)
obj_1.getName.call(null, 1, 2, 3)
apply()方法
1、可以进行函数的调用
2、可以改变this的指向,没有参数this指向window
3、可以改变this的指向,如果有一个参数,this指向当前参数
4、可以改变this的指向,如果有多个参数,this指向第一个参数,剩下的参数是数组
var name = '全局的'
var obj_1 = {
name: 'obj_1',
getName: function (x, y, z) {
console.log(x, y, z);
console.log(this);
console.log(this.name);
}
}
var obj_2 = {
name: 'obj_2'
}
// fn.apply()
obj_1.getName.apply()
obj_1.getName.apply(obj_2)
obj_1.getName.apply(null, [1, 2, 3])
bind()方法
1、不能进行函数的调用
2、可以改变this的指向,没有参数this指向window
3、可以改变this的指向,如果有一个参数,this指向当前参数
var name = '全局的'
var obj_1 = {
name: 'obj_1',
getName: function (x, y, z) {
console.log(x, y, z);
console.log(this);
console.log(this.name);
}
}
var obj_2 = {
name: 'obj_2'
}
// fn.bind()
var obj_3 = {
name: 'obj_3',
getName: function () {
console.log(this);
console.log(this.name);
}.bind(obj_2)
}
obj_3.getName()