前端开发 - this 指向问题(直接调用函数、对象方法、类方法)

一、直接调用函数

1、基本介绍
  1. 非严格模式:this 为 window

  2. 严格模式,this 为 undefined

2、演示
js 复制代码
function fn() {
    console.log(this);
}
fn();
复制代码
# 非严格模式下运行,输出结果

Window {window: Window, self: Window, document: document, name: '', location: Location, ...}

# 严格模式下运行,输出结果

undefined

二、对象方法

1、基本介绍
  1. 非严格模式:调用对象的方法,this 为该对象,取出方法后调用,this 为 window

  2. 严格模式:调用对象的方法,this 为该对象,取出方法后调用,this 为 undefined

2、演示
js 复制代码
const obj = {
    fn() {
        console.log(this);
    }
}
obj.fn();

console.log("----------");

const obj_fn = obj.fn;
obj_fn();
复制代码
# 非严格模式下运行,输出结果

{fn: ƒ}
----------
Window {window: Window, self: Window, document: document, name: '', location: Location, ...}

# 严格模式下运行,输出结果

{fn: ƒ}
----------
undefined

三、类方法

1、基本介绍
  1. 非严格模式:调用类的方法,this 为该类的实例,取出方法后调用,this 为 undefined

  2. 严格模式:调用类的方法,this 为该类的实例,取出方法后调用,this 为 undefined

  • 注:类的所有代码默认都是在严格模式下执行的
2、演示
js 复制代码
class Person {
    constructor(name, age) {
        this.name = name;
        this.age = age;
    }

    showInfo() {
        console.log(this);
        console.log(this.name, this.age);
    }
}
const p = new Person("张三", 18);
p.showInfo();

console.log("----------");

const person_showInfo = p.showInfo;
person_showInfo();
复制代码
# 非严格模式下运行,输出结果

Person {name: '张三', age: 18}
张三 18
----------
undefined
Uncaught TypeError: Cannot read properties of undefined (reading 'name')

# 严格模式下运行,输出结果

Person {name: '张三', age: 18}
张三 18
----------
undefined
Uncaught TypeError: Cannot read properties of undefined (reading 'name')
相关推荐
Lsir10110_14 分钟前
从按钮“点不动“讲起——深入理解 Qt 信号槽机制
开发语言·qt·信号处理
君科程序定做16 分钟前
用 IDL 处理高分一号(GF-1 / GF-1B/C/D)数据
c语言·开发语言
敲代码的嘎仔18 分钟前
用 Redis 合并写 + DelayQueue 延迟检测,把视频播放进度写库频率降到 1/60
java·开发语言·数据库·redis·缓存·音视频·高并发
代码中介商1 小时前
C++ 预约系统实战(一):项目总览与 C/S 架构设计
c语言·开发语言·c++
一拳不是超人1 小时前
一个没测暗色模式的 Bug,吃掉了我一半 谷歌扩展用户
前端·javascript·程序员
我叫汪枫1 小时前
RAG 进阶:切分、检索、重排序,以及它和 Agent、微调、MCP 都是什么关系
开发语言·python
弘毅 失败的 mian1 小时前
数组和指针基础
c语言·开发语言·经验分享·笔记
liangshanbo12151 小时前
React useState 函数式更新面试题整理
前端·react.js·前端框架
涛涛ing1 小时前
为什么你的页面在 Safari 上总出问题?Interop 2027 正在解决这个 20 年老毛病
前端
ai小陈1 小时前
Python 3.12与CUDA 12.8镜像实战:启动GPU实例后的五项自检
开发语言·人工智能·python·深度学习·ai·gpu算力