DIV CSS 佈局教程網

Node.js 中的 this 到底是什麼?一篇講清楚
編輯:關於JavaScript     

以下內容談的都是 Node.js 環境中的 this,而非瀏覽器裡 JavaScript 的 this——兩者的行為其實並不相同。

全域中的 this

 console.log(this); {} this.num = 10; console.log(this.num); 10 console.log(global.num); undefined 

在全域中,this 預設是一個空物件,而且和 global 物件沒有任何關係。那它究竟指向誰?我們後面再揭曉。

函式中的 this

 function fn(){ this.num = 10; } fn(); console.log(this); {} console.log(this.num); undefined console.log(global.num); 10 

在函式中,this 指向的是 global 物件,和全域中的 this 並不是同一個。也就是說,你在函式裡透過 this 定義的變數,相當於替 global 添加了一個屬性,此時已跟全域中的 this 無關。若還不相信,看下面這段程式碼:

 function fn(){ function fn2(){ this.age = 18; } fn2(); console.log(this); global console.log(this.age); 18 console.log(global.age); 18 } fn(); 

看吧,函式中的 this 確實指向 global。

建構函式中的 this

 function Fn(){ this.num = 998; } var fn = new Fn(); console.log(fn.num); 998 console.log(global.num); undefined 

在建構函式中,this 指向它的實例,而不是 global。

回到全域的 this

說到全域中的 this,其實和 Node.js 的作用域機制有關。回到正題:全域中的 this 指向的是 module.exports。

 this.num = 10; console.log(module.exports); {num:10} console.log(module.exports.num); 

至於為什麼全域的 this 會指向 module.exports,就得先理解更多關於 module.exports 的知識了,這裡先了解到這個程度,之後有機會再深入談 module。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved