今天早上看到公衆號推送了阮一峯老師的文章JavaScript 的 this 原理,文章不是很長因而研究了一下。javascript
看完本身的總結以下:html
this
== 就應運而生了。看到 ==js 容許函數體內部引用當前環境外的其餘變量== 想到以前本身總結過的關於做用域的知識點:java
令我產生困惑的兩句話:node
這裏的 ==執行做用域
== 與下文的 ==當前環境外的其餘變量
== 如何理解或者作區分?瀏覽器
翻閱紅寶書(第三版)p73,執行環境是 js 中最爲重要的一個概念,總結以下:模塊化
執行做用域
能夠理解爲 函數執行位置外部函數或者全局環境的做用域, 與函數本身的做用域(聲明時就被肯定了) 徹底是兩碼事衆所周知,瀏覽器環境下 全局環境下的 this 就是 window,沒有一點問題函數
// 瀏覽器環境下 var a = 'a' this.b = 'b' console.log(this.a) // a console.log(b) // b console.log(this===window) // true
// node 環境下 var x = 'xx' global.y = 'yy' // node 環境下輸出 console.log(y); // yy global 屬性掛載到了全局環境, console.log(global.x) // undefined 全局環境中定義的x 變量並無掛載到頂層對象global對象中 console.log(this === global) // false console.log(JSON.stringify(this))// {} 空對象,並非 global
查閱MDN發現:this
// node 環境下 function f1() { return this } console.log(f1() === global) // true console.log(this === global) // false
node 環境下只有定義在函數內部的 this 才指向 global ?
那麼, node 環境下 this 到底指向什麼?通過和導師的溝通
終於發現設計
// node 環境下 this.num = '10' global.test = '12' console.log(module.exports) // {num: "10"} console.log(this===module.exports) // true
那麼 node 環境下 this 爲何指向 module.exports
這和模塊化的設計又有什麼關係?code
發人深思...
天色已晚,且聽下回分解。