this指向问题讲解

牢记一点

this 永远指向最终调用它的对象

当然这话的前提条件是:不能是箭头函数。箭头函数没有 this、argument等。

实战训练

简单

例1

function example() {
const test = 'hahaha'
console.log(this.test) // undefined
console.log(this) // Window
}

example();

这里调用 example() 实际上就是 window.example() ,我们通常将 window 进行省略。

符合 this 永远指向最终调用它的对象 这个概念。

例2

const person = {
name: "张三",
say: function () {
console.log(this.name) // 张三
}
}
person.say()

同上,这里实际上是 window.person.say(),我们通常将 window 进行省略。

最后调用的是 person ,所以 this 指向的是 person 对象,输出 张三。

符合 this 永远指向最终调用它的对象 这个概念。

例3

const example = {
a: 10,
b: {
a: 12,
fn: function () {
console.log(this.a)
}
}
}
example.b.fn() // 12

同上,这里实际上是 window.example.b.fn(),我们通常将 window 进行省略。

最后调用的是 b ,所以 this 指向的是 b 对象,输出 12。

符合 this 永远指向最终调用它的对象 这个概念。

中等

例1

const example = {
a: 10,
b: {
// a: 12,
fn: function () {
console.log(this.a)
}
}
}
example.b.fn() // undefined

这个和【简单】中的【例3】有一点细微的区别,但这一个细微的区别却导致了不同的结果。

原理很简单,最后调用的是 b ,所以 this 指向的是 b 对象,但是 b 中并没有想要的属性,所以输出 undefined。

符合 this 永远指向最终调用它的对象 这个概念。

注意:即使 example 对象中拥有属性 a ,但是在 b 对象中它是访问不到的。不要用之前的局部函数能访问到外部属性的理解,这里处在的环境不一样。

例2

const example = {
a: 10,
b: {
a: 12,
fn: function () {
console.log(this.a)
}
}
}
const result = example.b.fn
result() // undefined

这里我们用了一个新属性来接收 example.b.fn ,然后对新属性进行了调用,这时候其实是 window.result() ,最终调用的是 window,所以输出了 undefined。

符合 this 永远指向最终调用它的对象 这个概念。

困难(函数有 return 返回值)

function Example() {
this.name = "张三"
return {}
}
const result = new Example()
console.log(result.name) // undefined
function Example() {
this.name = "张三"
return { hh: 'hh' }
}
const result = new Example()
console.log(result.name) // undefined

如果返回值是一个对象,那么 this 指向的就是那个返回的对象。

function Example() {
this.name = "张三"
return function () { }
}
const result = new Example()
console.log(result.name) // 无输出

如果返回值是一个对象,且为函数,会无输出。

function Example() {
this.name = "张三"
return { name: 'hh' }
}
const result = new Example()
console.log(result.name) // hh

如果返回值是一个对象,且包含有相应的属性,则输出这个属性值。

function Example() {
this.name = "张三"
return 123
}
const result = new Example()
console.log(result.name) // 张三
function Example() {
this.name = "张三"
return 'function () { }'
}
const result = new Example()
console.log(result.name) // 张三
function Example() {
this.name = "张三"
return undefined
}
const result = new Example()
console.log(result.name) // 张三

如果返回值不是一个对象那么 this 还是指向函数的实例。

function Example() {
this.name = "张三"
return null
}
const result = new Example()
console.log(result.name) // 张三

这是一个特例:函数返回值是 null,this 还是指向函数的实例。

function Example() {
this.name = "张三"
return Symbol
}
const result = new Example()
console.log(result.name) // Symbol
function Example() {
this.name = "张三"
return BigInt
}
const result = new Example()
console.log(result.name) // BigInt

如果返回值是 Number、String、BigInt等,会输出对应的返回值。