this是JS中的一个关键字,它始终指向一个对象,this是一个指针。
this的指向不是由定义this决定的,而是随着脚本的解析自动赋值的。
一、全局作用域下:this始终指向window对象
二、函数作用域下:函数被谁调用,this就指向谁
三、对象中的函数作用域下:this指向该方法所属的对象
四、在构造函数中:this始终指向新对象
五、自执行函数中:this指向window
六、箭头函数中:this是在定义是绑定到了父级对象上,不是在执行过程中绑定的。
改变this指向
1.call()
var obj = {
name: '张三'
}
function fn(a, b) {
console.log(this, a, b)
};
fn(1,2) // this:window a:1 b:2
fn.call(obj, 1, 2) // this:obj a:1 b:2
fn.call() // this:window a:undefined b:undefined
2.apply()
apply与call区别在于传参方式不一样,apply传的是一个数组
var obj = {
name: '张三'
}
function fn(a, b) {
console.log(this, a, b)
};
fn.apply(obj,[1,2]) // this:obj a:1 b:2
3.bind()
bind与call区别在于bind是返回一个函数,方便调用;call是立即执行
var obj = {
name: '张三'
}
function fn(a, b) {
console.log(this, a, b)
};
let newFn = fn.bind(obj, 1, 2)
newFn() // this:obj a:1 b:2
相同点
- 三者都是用来改变函数体内部 this 的指向;
- 三者第一个参数都是this要指向的对象,也就是想指定的上下文;
-
三者都可以利用后续参数传参
不同点
- bind是返回对应函数,便于稍后调用;apply、call则是立即调用
- apply、call接收参数的方式不一样
func.call(this, arg1, arg2);
func.apply(this, [arg1, arg2]);
- bind()提供永久的绑定,还会覆盖后面的call\apply命令。使用bind()绑定后,再使用call()或者apply()来不能重新绑定this
function returnThis () {
return this
}
var boss1 = { name: 'boss1'}
var boss1returnThis = returnThis.bind(boss1)
boss1returnThis() // boss1
var boss2 = { name: 'boss2' }
boss1returnThis.call(boss2) // still boss1
boss1returnThis.apply(boss2) // still boss1
boss1returnThis.bind(boss2) // boss2
原文链接:https://blog.csdn.net/qq_41995919/article/details/109703911