簡述
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