前端开发 - 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')
相关推荐
做前端的娜娜子31 分钟前
同一链接实现 PC Web 与移动 H5 自适应
前端·掘金·金石计划
爱吃牛肉的大老虎32 分钟前
Rust对象之结构体,枚举,特性
开发语言·后端·rust
小帅不太帅38 分钟前
架构没变、规模没变,DeepSeek V4 Flash 正式版凭什么暴涨 47 分?
前端·aigc·deepseek
bbq粉刷匠44 分钟前
HashMap 底层原理深度拆解(二):putVal 完整链路解析(懒加载 · 链表遍历 · 尾插法)
java·开发语言·哈希算法
jarvisuni1 小时前
DeepSeekFlash前端依旧拉垮,而且变慢了很多!
前端·javascript·算法
@三十一Y1 小时前
C++:红黑树的实现
开发语言·c++
乐观勇敢坚强的老彭2 小时前
C++信奥:开关门、开关灯问题
开发语言·c++·算法
冻柠檬飞冰走茶2 小时前
PTA基础编程题目集 7-31 字符串循环左移(C语言实现)
c语言·开发语言·数据结构·算法
卷福同学2 小时前
AI编程出海第二步:验证关键词能否做站
前端·人工智能·后端