From 043e2255d63bbb06844910832378b389fea41123 Mon Sep 17 00:00:00 2001 From: Leon Xu <6479451-leonxu260@users.noreply.gitlab.com> Date: Thu, 9 Sep 2021 14:05:03 -0700 Subject: [PATCH] doc: create a cavet arrow function section --- source/_posts/this关键字.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/source/_posts/this关键字.md b/source/_posts/this关键字.md index 0c523d2..cd03876 100644 --- a/source/_posts/this关键字.md +++ b/source/_posts/this关键字.md @@ -78,4 +78,22 @@ 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..."; +}); ``` \ No newline at end of file