this永远指向最终调用的函数所在的对象数组
① this指向的,永远只多是对象!bash
② this指向谁,永远不取决于this写在哪!而是取决于函数在哪调用。app
③ this指向的对象,咱们称之为函数的上下文context,也叫函数的调用者。函数
function Obj () {
console.log(this)
}
Obj() // window
复制代码
function Obj () {
console.log(this)
}
let obj = {
name: 'hello',
where: Obj
}
obj.where() // {name: "hello", where: ƒ}
复制代码
function Obj () {
console.log(this)
}
let obj = new Obj() // Obj{}
复制代码
function Obj () {
setTimeout(function () {
console.log(this)
}, 100)
}
let obj = {
name: 'hello',
where: Obj
}
obj.where() // window
复制代码
为什么在setTimeout和setInterval中this永远指向window呢?下面专门了解一下ui
由setTimeout()调用的代码运行在与所在函数彻底分离的执行环境上。这会致使,这些代码中包含的 this 关键字在非严格模式会指向 window (或全局)对象,严格模式下为 undefinedthis
function Obj () {
this.checkThis = function () {
console.log(this)
},
this.checkThisLast = function () {
setTimeout(function() {
console.log(this)
},100)
}
}
let obj = new Obj()
obj.checkThis() // Obj{}
obj.checkThisLast() // window
复制代码
如何解决setTimeout和setInterval中this的指向问题呢?spa
function Obj () {
let self = this, // this绑定给一个变量
this.checkThis = function () {
console.log(this)
},
this.checkThisLast = function () {
setTimeout(function() {
console.log(self)
},100)
}
}
let obj = new Obj()
obj.checkThis() // Obj{}
obj.checkThisLast() // Obj{}
复制代码
箭头函数不会建立本身的this,它只会从本身的做用域链的上一层继承thiscode
function Obj () {
this.checkThis = function () {
console.log(this)
},
this.checkThisLast = function () {
setTimeout(() => {
console.log(this)
},100)
}
}
let obj = new Obj()
obj.checkThis() // obj{}
obj.checkThisLast() // obj{}
复制代码
bind()用法是将函数绑定到对象上,会建立新的函数,函数体内的this值会被绑定到传入bind()的首个参数;f.bind(obj)至关于obj.f(),则f()的this指向obj对象
function Obj () {
this.checkThis = function () {
console.log(this)
},
this.checkThisLast = function () {
setTimeout(function () {
console.log(this)
}.bind(this),100)
}
}
let obj = new Obj()
obj.checkThis() // obj{}
obj.checkThisLast() // obj{}
复制代码