Files
Hexo-Butterfly/source/_posts/this关键字.md
T

121 lines
3.2 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
---
title: this关键字
date: 2021-09-09 12:25:28
tags:
- JavaScript
- 前端
description: JavaScript this关键字
top_img: >-
https://upload.wikimedia.org/wikipedia/commons/9/99/Unofficial_JavaScript_logo_2.svg
cover: >-
https://upload.wikimedia.org/wikipedia/commons/9/99/Unofficial_JavaScript_logo_2.svg
abbrlink: 75f5b5c3
categories:
- 前端
- JavaScript
update: 2021-10-06 14:58:30
---
# 一些有用的背景
- 函数的调用是执行构成函数体的代码,或者只是调用函数。
- 例如,parseInt函数调用是parseInt('15')。
- 调用的上下文是函数体中的值。
- 函数的作用域是函数体中可访问的变量和函数的集合。
# this
在“标准”语言中,这是当前对象的实例
```java
public int compareTo(Object other) {
return this - other;
}
```
在JavaScript中,这是函数调用的上下文
- 函数调用:alert('Hello World!')
- 方法调用:console.log('Hello World!')
- 构造函数调用:new RegExp ('d')
- 间接调用:alert.call(undefined, 'Hello World!')
# 关键字this
所有JavaScript代码实际上运行在我们可以用关键字this访问的“一个对象”内部
默认情况下,代码在全局窗口对象中运行(因此this === window)
事件监听器中附加的事件处理程序绑定到元素
在处理程序内部,该元素变成this
```javascript
function init() {
// this === 窗口
id("btn1").addEventListener("click", namedFunction)l
id("btn2").addEventListener("click", function() {
console.log("this === " + this); // this === #btn2
});
}
function namedFunction() {
console.log("this === " + this); // this === #btn1
}
```
### 更多JavaScript:this关关键字会发生什么
```javascript
let defaultReply = "Hello World";
button.addEventListener("click", function() {
draftReply(defaultReply);
});
```
```javascript
function draftReply(startingText) {
this.parentNode.appendNode( /*....*/);
// ...
}
// this === button
```
vs
```javascript
let defaultReply = "Hello World";
button.addEventListener("click", () => {
draftReply(defaultReply);
});
```
```javascript
function draftReply(startingText) {
this.parentNode.appendNode( /*....*/ );
// ...
}
```
### 警告:箭头函数不绑定this关键字
我们已经看到了“this”如何在事件处理程序中引用绑定元素。然而,箭头
函数不会以同样的方式绑定“this”。
```javascript
skittle.addEventListener("dblclick", function() {
// 正确!点击这个=== div.skittle
this.parentNode.removeChild(this);
id("result").textContent = ":O You ate a skittle...";
});
```
```javascript
skittle.addEventListener("dblclick", () => {
// 错误! this===窗口
this.parentNode.removeChild(this);
id("result").textContent = ":O You ate a skittle...";
});
```
### 用this比较不同的回调函数
```javascript
function init() {
// this === 窗口
id("btn1").addEventListener("click", namedFunction)l
id("btn2").addEventListener("click", function() {
console.log("this === " + this); // this === #btn2
});
id("btn3").addEventListener("click", () => {
console.log("this === " + this); // this === 窗口
});
}
function namedFunction() {
console.log("this === " + this); // this === #btn1
}
```