(前端)面试300问之(3)this的指向判断
2024-10-15 22:02:34
一、this的相关理解与解读
1、各角度看this。
1)ECMAScript规范:
this 关键字执行为当前执行环境的 ThisBinding。
2)MDN:
In most cases, the value of this is determined by how a function is called.
在绝大多数情况下,函数的调用方式决定了this的值。
3)其实,没必要记这些文邹邹的句子去理解【哎,很多我们懂的词语放在同一个句子里,我们可能就读不懂其意思了】。
我们只需记住一个魔法口诀 —— “this 永远指向最后调用它的那个对象” 就能理解 this 的指向问题。
二、this指向的判断。
1、this指向的判断流程图:
2、具体的例子:
1)普通函数 && 通过new关键字进行创建的:
class O {
constructor(name) {
this.name = name;
}
getName(){
console.log(this);
}
}
let o = new O('码农三少');
o.getName(); // {name: "码农三少"}
2)普通函数 && !通过new关键字进行创建 && 函数调用中使用上下文对象:
function fn() {
console.log(this);
}
let o = {
name: '码农三少',
fn: fn
}
window.fn(); // 上下文对象调用, 等价于直接调用 fn()。 {window: Window, self: Window, document: document, name: "", location: Location, …}
o.fn(); // 上下文对象调用。 {name: "码农三少", fn: ƒ}
3)普通函数 && !通过new关键字进行创建 && !函数调用中使用上下文对象:
function fn() {
console.log(this);
}
let o = {
name: '码农三少',
fn: fn
}
let newFn = o.fn;
newFn(); // 等同于 window.fn(); 和 fn(); 。 {window: Window, self: Window, document: document, name: "", location: Location, …}
4)箭头函数(指向它外层普通函数的this指向):
let o = {
name: '码农三少',
fn() {
return () => {
console.log(this)
}
}
}
let newFn = o.fn();
newFn(); // 这2行等价于 o.fn()(); 。{name: "码农三少", fn: ƒ}
5)使用了特殊函数(如bind、apply、call):
function fn() {
console.log(this);
}
let bindObj = {
name: '我是 bindObj , By 码农三少'
};
let applyObj = {
name: '我是 applyObj , By 码农三少'
};
let callObj = {
name: '我是 callObj , By 码农三少'
};
fn(); // 等价于 window.fn(); Window {window: Window, self: Window, document: document, name: "", location: Location, …}
fn.bind(bindObj)(); // {name: "我是 bindObj , By 码农三少"}
fn.apply(applyObj); // {name: "我是 applyObj , By 码农三少"}
fn.call(callObj); // {name: "我是 callObj , By 码农三少"}
三 更多
1)本人是20届本科生,大厂、创业公司都待过,现在是BAT的1名前端工程师(目前正往“全栈”方向发展,已开始写公司里的部分后端代码~)。
2)以下是个人整理的一些笔记和书籍(永久有效链接: https://pan.baidu.com/s/1SPc3umO6cZlBtoPylSaHzw 密码: eqee ,若失效的话可以到vx公众号 “码农三少” 回复 pdf 以进行最新资料的获取):
最新文章
- 传智播客DotNet面试题
- javascript学习之通过class获取元素
- java.sql.SQLException: No suitable driver 问题解决
- sql创建删除修改表的基本操作
- 03-position和anchorPoint
- Javascript 拖拽的一些高级的应用——逐行分析代码,让你轻松了解拖拽的原理
- HDU 1159 Common Subsequence:LCS(最长公共子序列)
- 常用px,pt,em换算及区别
- Java面向对象 包
- HTML5之appcache语法理解/HTML5应用程序缓存/manifest缓存文件官方用法翻译
- 使用VMware通过vmdk文件创建XP虚拟机
- Codeforces.468C.Hack it!(构造)
- faiss CPU版本+GPU版本安装
- .net项目错误:找不到方法:“System.Net.Http.HttpClient stellar_dotnet_sdk.Server.get_HttpClient()
- CentOS 7.2通过yum安装MairaDB 10.1
- Linux文件IO与通用块层的请求合并
- Kubernetes探索学习002--Kubernetes的基本使用
- C++ 实现memcpy和strcpy
- RedHat7.4最小化安装yum源不可用问题解决
- x-pack本地安装方式