一、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 以进行最新资料的获取):

最新文章

  1. 传智播客DotNet面试题
  2. javascript学习之通过class获取元素
  3. java.sql.SQLException: No suitable driver 问题解决
  4. sql创建删除修改表的基本操作
  5. 03-position和anchorPoint
  6. Javascript 拖拽的一些高级的应用——逐行分析代码,让你轻松了解拖拽的原理
  7. HDU 1159 Common Subsequence:LCS(最长公共子序列)
  8. 常用px,pt,em换算及区别
  9. Java面向对象 包
  10. HTML5之appcache语法理解/HTML5应用程序缓存/manifest缓存文件官方用法翻译
  11. 使用VMware通过vmdk文件创建XP虚拟机
  12. Codeforces.468C.Hack it!(构造)
  13. faiss CPU版本+GPU版本安装
  14. .net项目错误:找不到方法:“System.Net.Http.HttpClient stellar_dotnet_sdk.Server.get_HttpClient()
  15. CentOS 7.2通过yum安装MairaDB 10.1
  16. Linux文件IO与通用块层的请求合并
  17. Kubernetes探索学习002--Kubernetes的基本使用
  18. C++ 实现memcpy和strcpy
  19. RedHat7.4最小化安装yum源不可用问题解决
  20. x-pack本地安装方式

热门文章

  1. python中return的返回和执行
  2. 【数据结构与算法Python版学习笔记】树——利用二叉堆实现优先级队列
  3. .Net Core中使用ElasticSearch(一)
  4. Windows10使用技巧
  5. 剑指offer:JZ9 用两个栈实现队列
  6. sonar-project.propertie分析参数
  7. Shadertoy 教程 Part 3 - 矩形和旋转
  8. 从零开始 DIY 智能家居 - 基于 ESP32 的智能语音合成播报模块
  9. 四. 几个Promise常用API的介绍与使用
  10. tomcat9启动报错too low setting for -Xss