简述
this 是 JavaScript 语言的一个关键字。它是函数运行时,在函数体内部自动生成的一个对象,只能在函数体内部使用
this 的指向在函数定义的时候是确定不了的,只有函数执行的时候才能确定 this 到底指向谁
函数的不同使用场合,this 有不同的值。总的来说,this 就是函数运行时所在的环境对象
一般的函数调用
一般的函数调用属于全局性调用,因此 this 就代表全局对象 window
var a = 1
function fn() {
var a = 2
console.log(this) // window this ——> window
console.log(this.a) // 1 this ——> window
}
fn()
作为对象方法的调用
函数作为某个对象的方法调用,此时 this 指向上级对象
var a = 1
var obj = {
a: 2,
fn: function() {
console.log(this) // {a: 1, fn: ƒ} this ——> obj
console.log(this.a) // 2 this ——> obj
}
}
obj.fn()
函数作为某个对象的方法,赋值给一个全局变量,此时 this 指向 window
var a = 1
var obj = {
a: 2,
fn: function() {
console.log(this) // window this ——> window
console.log(this.a) // 1 this ——> window
}
}
var foo = obj.fn()
foo()
构造函数调用
所谓构造函数,就是通过这个函数,可以生成一个新对象。这时,this 就指向这个新对象
function Fn() {
this.a = 1
console.log(this) // Fn {a: 1} this ——> fn
}
var fn = new Fn()
console.log(fn.a) // 1
箭头函数中没有this
箭头函数中没有 this,所以不能用作构造函数,否则会报错
var Fn = ()=> {
console.log(this)
}
var fn = new Fn() // Fn is not a constructor
setTimeout & setInterval
延时函数内部的回调函数的 this 指向全局对象 window
var a = 1
setInterval(function() {
console.log(this) // window this ——> window
console.log(this.a) // 1 this ——> window
}, 1000)
setTimeout(function() {
console.log(this) // window this ——> window
console.log(this.a) // 1 this ——> window
}, 1000)
当this遇到return
如果返回值是一个对象,那么 this 指向的就是那个返回的对象,如果返回值不是一个对象,那么 this 指向函数的实例
function Fn()
{
this.a = 1
return {}
}
var fn = new Fn()
console.log(fn.a) // undefined this ——> {}
function Fn()
{
this.a = 1
return function() {}
}
var fn = new Fn()
console.log(fn.a) // undefined this ——> function() {}
function Fn()
{
this.a = 1
return ''
}
var fn = new Fn()
console.log(fn.a) // 1 this ——> fn