diff --git a/source/_posts/this关键字.md b/source/_posts/this关键字.md index bf3faba..e01feac 100644 --- a/source/_posts/this关键字.md +++ b/source/_posts/this关键字.md @@ -29,4 +29,23 @@ public int compareTo(Object other) { - 函数调用:alert('Hello World!') - 方法调用:console.log('Hello World!') - 构造函数调用:new RegExp ('d') -- 间接调用:alert.call(undefined, 'Hello World!') \ No newline at end of file +- 间接调用: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 +} +``` \ No newline at end of file