前端开发 - 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')
相关推荐
小黑的铁粉2 小时前
ecahrts图形多的页面,怎么解决数据量大的渲染问题?
前端·echarts
mjhcsp2 小时前
C++ Dancing Links(舞蹈链):从原理到实战的深度解析
开发语言·c++·dancing links
橙汁味的风2 小时前
1计算机网络引言
开发语言·计算机网络·php
低保和光头哪个先来2 小时前
TinyEditor 篇1:实现工具栏按钮向服务器上传图片
服务器·开发语言·前端·javascript·vue.js·前端框架
还是大剑师兰特2 小时前
vue3+vite+JS,使用Echarts封装一个饼图,父子组件联动
javascript·vue.js·echarts
忡黑梨2 小时前
BUUCTF_reverse_[MRCTF2020]Transform
c语言·开发语言·数据结构·python·算法·网络安全
于先生吖2 小时前
Java 同城服务同城租房系统源码 完整项目实现
java·开发语言
A黄俊辉A2 小时前
webstorm+vue+esLint+pretter配置
前端·vue.js·webstorm
TYFHVB122 小时前
2026六大主流CRM横评,五大核心维度深度解析
大数据·前端·数据结构·人工智能