一、window调用
console.log(this) // window
function a() {
console.log(this) // window
}
a() // window.a() 只不过window可以隐藏了
二、变量调用(指向变量)
let a = {
name: "郑建",
fn: function() {
console.log(this) // this指向变量a
}
}
a.fn()
三、this永远指向离它最近的上一级 (也就是上一个调用者)
var j = {
a: 10,
b: {
a: 12,
fn: function() {
console.log(this)
}
}
}
j.b.fn() // 指向b因为b是fn的上一级 跟b后面的j毛关系都没有
四、箭头函数没有自己的this,会取父函数的this
var id = 66
function fn5() {
setTimeout(() => {
console.log(this.id) // 打印出66
}, 500)
}
fn5({id: 22})
五、改变this的指向
- call
var id = 66
function fn5() {
setTimeout(() => {
console.log(this.id)
}, 500)
}
fn5({id: 22}) // 打印出66
fn5.call({id: 22}) // 打印出22
2.apply
3.bind
区别: call、apply:这两种方法改变了this之后还会调用一次
bind,反之