3.3 KiB
3.3 KiB
title, date, tags, description, top_img, cover, abbrlink, categories, update
| title | date | tags | description | top_img | cover | abbrlink | categories | update | ||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| this关键字 | 2021-09-09 12:25:28 |
|
JavaScript this关键字 | https://upload.wikimedia.org/wikipedia/commons/9/99/Unofficial_JavaScript_logo_2.svg | https://upload.wikimedia.org/wikipedia/commons/9/99/Unofficial_JavaScript_logo_2.svg | 75f5b5c3 |
|
2021-10-06 14:58:30 |
一些有用的背景
- 函数的调用是执行构成函数体的代码,或者只是调用函数。
- 例如,parseInt函数调用是parseInt('15')。
- 调用的上下文是函数体中的值。
- 函数的作用域是函数体中可访问的变量和函数的集合。
this
在“标准”语言中,这是当前对象的实例
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
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关关键字会发生什么
let defaultReply = "Hello World";
button.addEventListener("click", function() {
draftReply(defaultReply);
});
function draftReply(startingText) {
this.parentNode.appendNode( /*....*/);
// ...
}
// this === button
vs
let defaultReply = "Hello World";
button.addEventListener("click", () => {
draftReply(defaultReply);
});
function draftReply(startingText) {
this.parentNode.appendNode( /*....*/ );
// ...
}
警告:箭头函数不绑定this关键字
我们已经看到了“this”如何在事件处理程序中引用绑定元素。然而,箭头 函数不会以同样的方式绑定“this”。
skittle.addEventListener("dblclick", function() {
// 正确!点击这个=== div.skittle
this.parentNode.removeChild(this);
id("result").textContent = ":O You ate a skittle...";
});
skittle.addEventListener("dblclick", () => {
// 错误! this===窗口
this.parentNode.removeChild(this);
id("result").textContent = ":O You ate a skittle...";
});
用this比较不同的回调函数
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
}