前端开发 - 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')
相关推荐
luj_17682 分钟前
心形曲线轨迹控制三大关键技术
c语言·开发语言·c++·经验分享·算法
谙忆102412 分钟前
前端图片直传对象存储:OSS/S3 预签名 URL、STS 临时凭证与回调校验
前端
Mininglamp_271838 分钟前
Claude Code 封禁中国开发者之后:本地 AI 编程工具的替代方案实测
开发语言·人工智能·windows·开源软件·ai-native
思麟呀1 小时前
C++17(三)if constexpr+折叠表达式
开发语言·c++
醉城夜风~1 小时前
Java详解经典算法题:接雨水(三种实现方案+原理剖析)
java·开发语言·算法
qydz111 小时前
杰理开发基础知识(3)
开发语言·嵌入式开发·杰理科技
贾斯汀frank1 小时前
C# 15 类型系统改进:Union Types
开发语言·windows·c#
阿里嘎多学长1 小时前
2026-07-10 GitHub 热点项目精选
开发语言·程序员·github·代码托管
CHNE_TAO_EMSM1 小时前
Android studio 打开文件时自动下载源码
前端·javascript·android studio
CHHH_HHH2 小时前
【C++11】深入解析C++可变参数模板
开发语言·c++·算法·stl·c++11