前端开发 - this 指向问题(直接调用函数、对象方法、类方法)
一、直接调用函数1、基本介绍非严格模式this 为 window严格模式this 为 undefined2、演示functionfn(){console.log(this);}fn();# 非严格模式下运行输出结果 Window {window: Window, self: Window, document: document, name: , location: Location, …}# 严格模式下运行输出结果 undefined二、对象方法1、基本介绍非严格模式调用对象的方法this 为该对象取出方法后调用this 为 window严格模式调用对象的方法this 为该对象取出方法后调用this 为 undefined2、演示constobj{fn(){console.log(this);}}obj.fn();console.log(----------);constobj_fnobj.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.namename;this.ageage;}showInfo(){console.log(this);console.log(this.name,this.age);}}constpnewPerson(张三,18);p.showInfo();console.log(----------);constperson_showInfop.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)
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2412015.html
如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!