你好,我是南一。这是我在准备面试八股文的笔记,如果有发现错误或者可完善的地方,还请指正,万分感谢🌹
this 指向
this 只有调用之后才知道指向谁,一般指向函数调用者
1.没人调用默认指向window
function a() {
let aa = 2
console.log(this); // window
console.log(this.aa); //undefined
}
a()
2.严格模式 this指向undefined
function a() {
"use strict"
let aa = 2
console.log(this); //undefined
console.log(this.aa); //TypeError: Cannot read properties of undefined (reading 'aa')
}
a()
3.对象b调用函数,所以输出1
const obj = {
a: 2,
b: {
a: 1,
fn: function () {
console.log(this.a); // 1
}
}
}
obj.b.fn()
4.还是对象b调用函数,没找到a元素所以输出undefined
const obj = {
a: 2,
b: {
fn: function () {
console.log(this.a); // undefined
}
}
}
obj.b.fn()
5.setTimeout里匿名函数没有直接调用者,this指向window
const obj = {
a: 2,
b: function () {
setTimeout(function () {
console.log(this); //window
})
}
}
obj.b()
6.箭头函数只会从自己的作用域链的上一层继承this。
const obj = {
a: 2,
b: function () {
setTimeout(() => {
console.log(this); // obj
})
}
}
obj.b()
const obj = {
a: 2,
b: () => {
setTimeout(() => {
console.log(this); //window
})
}
}
obj.b()
7.构造函数内的this会指向new出来的实例对象
function C(){
this.a = 37;
}
var o = new C();
console.log(o.a); // 37
这里想要深入了解new运算符可以看我的下一篇文章new 运算符模拟实现
8.call、apply、bind可以改变this指向
想要更好理解call、apply、bind的执行过程是怎么实现的,可以看看我的另外两篇文章。
call 经典应用,构造函数实现继承
function Father(name) {
this.sex = 'man'
this.name = name
}
function Son(name) {
Father.call(this, name) // call 第一个参数就是要指向的对象,后面的参数传递给改变this指向的函数
}
const boy = new Son('Mike')
console.log(boy.sex, boy.name); // man Mike
从ES规范的角度解读this
如果感兴趣,可以看看冴语大佬写的JavaScript深入之从ECMAScript规范解读this