前端开发 - 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')
相关推荐
5系暗夜孤魂1 分钟前
系统越复杂,越需要“边界感”:从 Java 体系理解大型工程的可维护性本质
java·开发语言
无巧不成书021840 分钟前
C语言零基础速通指南 | 1小时从入门到跑通完整项目
c语言·开发语言·编程实战·c语言入门·零基础编程·c语言速通
三雷科技1 小时前
使用 `dlopen` 动态加载 `.so` 文件
开发语言·c++·算法
wellc1 小时前
java进阶知识点
java·开发语言
RopenYuan1 小时前
FastAPI -API Router的应用
前端·网络·python
听风吹等浪起1 小时前
用Python和Pygame从零实现坦克大战
开发语言·python·pygame
灰色小旋风1 小时前
力扣合并K个升序链表C++
java·开发语言
_MyFavorite_1 小时前
JAVA重点基础、进阶知识及易错点总结(28)接口默认方法与静态方法
java·开发语言·windows
取码网1 小时前
最新在线留言板系统PHP源码
开发语言·php