I've just seen a weird behaviour of the this
keyword in NodeJS environment. I'm listing them with code. I've run this codes with NodeJS v6.x
, with a single JavaScript
file.
While testing with one line of code as follows, whether with or without the 'use strict'
statement, this points to an empty object {}
.
console.log(this)
But, when I'm running the statement within a self executing function like,
(function(){
console.log(this);
}());
It's printing a really big object. Seems to me the Global execution context object created by NodeJS
environment.
And while executing the above function with a 'use strict'
statement, expectedly it's printing undefined
(function(){
'use strict';
console.log(this);
}());
But, while working with browser (I've tested only with Chrome
), the first three examples yield the window
object and the last one gave undefined
as expected.
The behaviour of the browser is quite understandable. But, in case of NodeJS
, does it not create the execution context, until I'm wrapping inside a function?
So, most of the code in NodeJS
runs with an empty global object
?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…