Difference between window (browser) and global (Node.js) objects

2024/2/27 7:43:23

I am trying to understand how Javascript works under the hood so I've been playing around a bit. For example, the following code generates different outputs when in Chrome's console or when in Node.js:

var length = 10;
function fn () {console.log (this.length);
}
fn();

In Chrome, I get the value 10 logged, while in Node, this is undefined. Is it because in the window object, global variables are treated as properties of window, while in Node, the global object has a different behavior? If so, what is happening in the global object, and how could I get a similar behavior to window, without declaring global.length? I am doing this just as an exercise, there is no other purpose than understanding.

Answer

The reason for the difference is that the top-level scope in a browser script is the global scope, but the top-level scope in a Node.js file is module scope. (By default it's an old-style Node.js module which is in loose mode, but in modern versions of Node.js you can opt into JavaScript standard module scope, which is in strict mode.)

At global scope, var creates a property on the global object, which you can access via the window global, via this at global scope, or via this in a loose-mode function you call without doing anything specific to set this. Your call to fn above is that last category: a loose-mode function called without setting this.

But at Node.js module scope, var just creates a var in the module, it doesn't create a global or a property on the global object. It's like doing this:

(function() { // The wrapper Node.js provides node-style modules
// This is "module" scope
var foo = 10;
function fn () {
console.log (this.foo);
}
fn();
})();         // End of the wrapper

(Why did I change length to foo? Because by default, window has a length property [the number of frames the window contains], which confused matters. :-) )

So it's just a difference in scope.


You can also use module scope on modern browsers, including Chrome, via type="module" on the script tag. But since JavaScript standard modules are always in strict mode, the this inside the call to fn would be undefined, causing an error:

<script type="module">
var length = 10;
function fn () {
console.log(this);        // undefined
console.log(this.length); // TypeError
}
fn();
</script>

http://en.ppmy.cn/q/42221.html

Related Q&A

How do I get the clicked element with inline HTML onclick and jQuery?

Im creating a tags with this code:$(#td + id).append(<p><a href="#" onclick="excluirArquivo(\ + response + \); return false;"><img src="/erp/proposta/media/image…

Does curry function in javascript uses principle of closure? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.Want to improve this question? Update the question so it focuses on one problem only by editing this post.Closed 7…

The execution sequence when returning a Promise object in promise then mehod [duplicate]

This question already has answers here:What is the difference between returned Promise?(2 answers)ES6 promise execution order for returned values(2 answers)What is the order of execution in JavaScript…

Using sequelize cli with typescript

Im trying to use sequelize with typescript, but dont know how. I installed a package named sequelize-cli-typescript, but it does not work with sequelize v6. And I know it is better to use migrations to…

clipboard copy does not work in jquery ajax success method

I want to copy a card number into the clipboard so that I can paste it in Notepad. The code which I got from the internet works very well if tried in the developer toolbar of the browser. However if I …

How do event handlers in JavaScript get processed by the event loop?

Im a little bit confused about how browsers handle JavaScript events.Lets say I have two event handlers attached to buttons A and B. Both event handlers take exactly the same time to complete. If I cli…

how to highlight a chosen line on a leaflet map?

I want to draw a map with few routes drawn on it.I want to have a dropbox with numbers 1,..,nwhen an item in the dropbox is chosen, the corresponding route is highlighted on the map.I have started usin…

Bootstrap collapse and ui-router

I have issue with ui-router and using bootstrap collapse. <div class="panel panel-default" id="accordion" ><div role="tab" id="headingOne"><a role…

Why the interval will become faster and faster if I keep setting new interval

I am doing a very simple timer with two buttons: stop and set. Here is the code:<h1>0</h1><button onclick = set()>Set</button><button onclick = stop()>Stop</button>v…

Windows Scripting: VBScript, DOS, JS, Python,

Say you were mainly a C-syntax like programmer and Linux systems administrator, and you were tasked with creating some simple automation tasks on Windows (monitoring of back-up files, process monitorin…