最近在用Nodejs進行APP運維服務管理系統開發時發現,nodejs中的this經常會變,查了下資料后發現this在不同的代碼位置中代表不同的涵義,在實際運用過程中可以用var self = this接住函數外的this,在函數內用self.xxx繼續使用詳情如下,
以下內容都是關於在nodejs中的this而非javascript中的this,nodejs中的this和在瀏覽器中javascript中的this是不一樣的。
在全局中的this
|
1
2
3
4
|
console.log(
this
); {}
this
.num = 10;
console.log(
this
.num); 10
console.log(global.num); undefined
|
全局中的this默認是一個空對象。並且在全局中this與global對象沒有任何的關系,那么全局中的this究竟指向的是誰?在本章節后半部分我們會講解。
在函數中的this
|
1
2
3
4
5
6
7
|
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已經沒有關系了。
如果不相信,看下面這段代碼可以證明。
|
1
2
3
4
5
6
7
8
9
10
|
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
|
1
2
3
4
5
6
|
function
Fn(){
this
.num = 998;
}
var
fn =
new
Fn();
console.log(fn.num); 998
console.log(global.num); undefined
|
在構造函數中this指向的是它的實例,而不是global。
我們現在可以聊聊關於全局中的this了,說到全局中的this,其實和Nodejs中的作用域有一些關系,如果你想了解Nodejs中關於作用域的信息可以看探討Nodejs中的作用域問題。這篇文章。
回到正題,全局中的this指向的是module.exports。
|
1
2
3
|
this
.num = 10;
console.log(module.exports); {num:10}
console.log(module.exports.num);
|
