简述
this
是 JavaScript
语言的一个关键字。它是函数运行时,在函数体内部自动生成的一个对象,只能在函数体内部使用
this
的指向在函数定义的时候是确定不了的,只有函数执行的时候才能确定 this
到底指向谁
函数的不同使用场合,this
有不同的值。总的来说,this
就是调用函数的那个对象
一般的函数调用
一般的函数调用属于全局性调用,此时 this
指向全局对象 window
,严格模式下,this
指向 undefined
var a = 1
function fn() {
var a = 2
console.log(this) // window this ——> window
console.log(this.a) // 1 this ——> window
}
fn()
// 严格模式
'use strict'
function fn() {
console.log(this) // undefined this ——> undefined
}
fn()
DOM元素绑定事件调用
var box = document.getElementById("box");
box.onclick = function () {
console.log(this); // this ——> 当前DOM元素 box
}
作为对象方法的调用
函数作为某个对象的普通方法调用,此时 this
指向上级对象,严格模式下亦是如此
var a = 1
var obj = {
a: 2,
fn: function() {
console.log(this) // {a: 2, fn: ƒ} this ——> obj
console.log(this.a) // 2 this ——> obj
}
}
obj.fn()
'use strict'
var a = 1
var obj = {
a: 2,
fn: function() {
console.log(this) // {a: 2, fn: ƒ} this ——> obj
console.log(this.a) // 2 this ——> obj
}
}
obj.fn()
箭头函数作为某个对象的方法调用,此时 this
指向 window
,严格模式下亦是如此
箭头函数作为某个对象的方法,,赋值给一个全局变量,此时 this
也是指向 window
,严格模式下亦是如此
// 一、
var a = 1
var obj = {
a: 2,
fn: () => {
console.log(this) // window this ——> window
console.log(this.a) // 1 this ——> window
}
}
obj.fn()
// 二、
var a = 1
var obj = {
fn: () => {
console.log(this) // window this ——> window
console.log(this.a) // 1 this ——> window
}
}
var foo = obj.fn
foo()
函数作为某个对象的方法,赋值给一个全局变量,此时 this
指向 window
,严格模式下,this
指向 undefined
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()
// 严格模式
'use strict'
var obj = {
fn: function () {
console.log(this) // undefined this ——> undefined
}
}
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 实例化对象