(前端)面试300问之(3)this的指向判断

一、this的相关理解与解读

1、各角度看this。

1)ECMAScript规范:

this 关键字执行为当前执行环境的 ThisBinding。

2)MDN:

In most cases, the value of this is determined by how a function is called.

在绝大多数情况下,函数的调用方式决定了this的值。

3)其实,没必要记这些文邹邹的句子去理解【哎,很多我们懂的词语放在同一个句子里,我们可能就读不懂其意思了】。

我们只需记住一个魔法口诀 ------ "this 永远指向最后调用它的那个对象" 就能理解 this 的指向问题。

二、this指向的判断。

1、this指向的判断流程图:

判断this指向.png

2、具体的例子:

1)普通函数 && 通过new关键字进行创建的:
class O {
    constructor(name) {
        this.name = name;
    }
    getName(){
        console.log(this);
    }
}

let o = new O('码农三少');
o.getName(); // {name: "码农三少"}
2)普通函数 && !通过new关键字进行创建 && 函数调用中使用上下文对象:
function fn() {
    console.log(this);
}

let o = {
    name: '码农三少',
    fn: fn
}

window.fn();    // 上下文对象调用, 等价于直接调用 fn()。 {window: Window, self: Window, document: document, name: "", location: Location, ...}
o.fn();       // 上下文对象调用。 {name: "码农三少", fn: ƒ}
3)普通函数 && !通过new关键字进行创建 && !函数调用中使用上下文对象:
function fn() {
    console.log(this);
}

let o = {
    name: '码农三少',
    fn: fn
}
let newFn = o.fn;
newFn(); // 等同于 window.fn(); 和 fn(); 。 {window: Window, self: Window, document: document, name: "", location: Location, ...}
4)箭头函数(指向它外层普通函数的this指向):
let o = {
    name: '码农三少',
    fn() {
        return () => {
            console.log(this)
        }
    }
}

let newFn = o.fn();
newFn(); // 这2行等价于 o.fn()(); 。{name: "码农三少", fn: ƒ}
5)使用了特殊函数(如bind、apply、call):
function fn() {
    console.log(this);
}

let bindObj = {
    name: '我是 bindObj , By 码农三少'
};

let applyObj = {
    name: '我是 applyObj , By 码农三少'
};

let callObj = {
    name: '我是 callObj , By 码农三少'
};

fn(); // 等价于 window.fn(); Window {window: Window, self: Window, document: document, name: "", location: Location, ...}
fn.bind(bindObj)(); // {name: "我是 bindObj , By 码农三少"}
fn.apply(applyObj); // {name: "我是 applyObj , By 码农三少"}
fn.call(callObj); // {name: "我是 callObj , By 码农三少"}

喜欢的朋友记得点赞、收藏、关注哦!!!

相关推荐
wending-Y42 分钟前
一文速通calcite结合flink理解SQL从文本变成执行计划详细过程
java·sql·flink
西猫雷婶1 小时前
python画图|3D surface基础教程
开发语言·python
小于负无穷2 小时前
Go 中 Gin 框架的使用指南
开发语言·后端·golang·gin
周bro2 小时前
vue3使用panolens.js实现全景,带有上一个下一个,全屏功能
开发语言·javascript·ecmascript
golove6662 小时前
Spring Cloud集成Gateaway
java·spring·spring cloud
常某某的好奇心3 小时前
54. 二叉搜索树的第 k 大节点
算法
白总Server3 小时前
rust解说
linux·开发语言·后端·golang·rust·debian·php
金庆3 小时前
Rust Pin
开发语言·后端·rust
娇娇yyyyyy3 小时前
G1: Yunli‘s Subarray Queries (easy version)(1900)(定长区间众数)
算法
Lill_bin3 小时前
CAS机制:并发编程中的原子操作
java·服务器·开发语言·windows·算法·微服务