一、直接调用函数
1、基本介绍
非严格模式:this 为 window
严格模式,this 为 undefined
2、演示
functionfn(){console.log(this);}fn();# 非严格模式下运行,输出结果 Window {window: Window, self: Window, document: document, name: '', location: Location, …}# 严格模式下运行,输出结果 undefined二、对象方法
1、基本介绍
非严格模式:调用对象的方法,this 为该对象,取出方法后调用,this 为 window
严格模式:调用对象的方法,this 为该对象,取出方法后调用,this 为 undefined
2、演示
constobj={fn(){console.log(this);}}obj.fn();console.log("----------");constobj_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、演示
classPerson{constructor(name,age){this.name=name;this.age=age;}showInfo(){console.log(this);console.log(this.name,this.age);}}constp=newPerson("张三",18);p.showInfo();console.log("----------");constperson_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')