上下文(this)指向
函数的this由调用函数的方式决定,函数没有被调用时,无法确定this的指向。
规则 | this |
---|---|
对象.函数() | 该对象 |
函数() | window |
数组[下标]() | 数组 |
IIFE | window |
定时器,延时器 | window |
DOM事件处理函数 | 绑定的DOM元素 |
call、apply、bind | 第一个参数 |
1.通过对象打点的方式调用函数
obj.fn()
var obj = {
a:1,
b:2,
fun:function(){
console.log(this.a, this.b)
}
}
var a = 3;
var b = 4;
obj.fun() // 1 2
2.使用圆括号直接调用函数
对于直接使用圆括号调用的函数,this是window对象
fn()
let obj1 = {
a:1,
b:2,
fn:function(){
console.log(this.a + this.b)
}
}
// 注意声明时用的关键字 var / let,const 有所不同
var a = 3
var b = 4
let fn = obj1.fn
fn() // 7
3.数组(类数组)枚举出函数进行调用
对于调用数组里面的函数,this则是这个数组
arr[0]()
var obj = {
a:1,
b:2,
arr :[1,2,function(){
console.log(this) // this是arr这个数组,而不是调用者obj
}]
}
obj.arr[2]() // 输出 arr
function fun(){
arguments[3]()
}
fun(1,2,3,function(){
console.log(this) // this是arguments这个类数组,而不是window
})
4.IIFE中的函数
对于IIFE立即执行函数里的this,是window对象
(function(){
})()
var a= 1
var obj = {
a:2,
fun:(function(){
// 这里的this是window对象
var a = this.a
return function(){
// 这里的this是调用者obj,a是闭包里的a
console.log(a, this.a)
}
})()
}
obj.fun() // 1 2
5.定时器、延时器调用函数
对于定时器、延时器调用函数,this是window对象
setInterval(fn, delay)
setTimeout(fn, delay)
var obj = {
a:1,
b:2,
fun:function(){
console.log(this.a , this.b)
}
}
var a =3
var b =4
setTimeout(obj.fun, 2000) // 3 4
var obj = {
a:1,
b:2,
fun:function(){
console.log(this.a , this.b)
}
}
var a =3
var b =4
setTimeout(function(){
console.log(this.a) // 3
obj.fun()
}, 2000) // 1 2
6.事件处理函数的this
对于事件处理函数的this,是绑定事件的DOM元素
DOM.onclick = function () {
}
function () {
this.style.color = 'red' // this是绑定此事件的DOM元素
}
7.改变this函数this
call、apply和bind指定this
function sum(){
console.log(this)
console.log(arguments[0] + arguments[1])
}
var obj = {
a:1,
b:2
}
sum.call(obj, 3 , 4) // 7
sum.apply(obj, [5, 6]) // 11
sum.bind(obj, 7, 8)() // 15
call、apply和bind的区别:
call、apply和bind的第一个参数都是this的指向,而call和bind的参数写在第一个参数后面,通过逗号隔开。apply的参数通过一个数组或类数组传入,写在一个参数后面。另外call和apply是立即执行,而bind返回的是函数,需要调用。