一、直接调用函数
1、基本介绍
-
非严格模式:this 为 window
-
严格模式,this 为 undefined
2、演示
js
function fn() {
console.log(this);
}
fn();
# 非严格模式下运行,输出结果
Window {window: Window, self: Window, document: document, name: '', location: Location, ...}
# 严格模式下运行,输出结果
undefined
二、对象方法
1、基本介绍
-
非严格模式:调用对象的方法,this 为该对象,取出方法后调用,this 为 window
-
严格模式:调用对象的方法,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、基本介绍
-
非严格模式:调用类的方法,this 为该类的实例,取出方法后调用,this 为 undefined
-
严格模式:调用类的方法,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')