Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are functions not available in global object?

This script has different behavior based on whether it's run from the node js shell or stored in a script file passed to node.

Script:

var a = 1;
function b(){return 1;}
for(var k in global) console.log(k);

Output in shell (only last 4 lines are relevant IMO. Each of the 3 lines were copy/pasted sequentially into a node REPL instance running in Terminal on Mac OS X):

ArrayBuffer
Int8Array
Uint8Array
Int16Array
Uint16Array
Int32Array
Uint32Array
Float32Array
Float64Array
DataView
global
process
GLOBAL
root
Buffer
setTimeout
setInterval
clearTimeout
clearInterval
console
module
require
a
_
b
k

Output when run as a saved script (called node myscript.js from bash on Mac OS X):

ArrayBuffer
Int8Array
Uint8Array
Int16Array
Uint16Array
Int32Array
Uint32Array
Float32Array
Float64Array
DataView
global
process
GLOBAL
root
Buffer
setTimeout
setInterval
clearTimeout
clearInterval
console

Why are they different, and why can't my script see a and b in global?

EDIT: Adding an additional statement c = 2 changed the output. c was visible in both methods of running the script. This still doesn't explain a and b's presence when running the script from the shell though.

like image 769
Trindaz Avatar asked May 07 '12 18:05

Trindaz


People also ask

Are functions global in JavaScript?

Everything in JS is bound to containing scope. Therefore, if you define a function directly in file, it will be bound to window object, i.e. it will be global.

Can a function be inside an object?

You can call a function inside an object by declaring the function as a property on the object and invoking it, e.g. obj. sum(2, 2) . An object's property can point to a function, just like it can point to a string, number or other values.

Is a JavaScript global variable is not accessible from any function?

Global variables can be accessed from anywhere in a JavaScript program.


1 Answers

Basically it's because Node's REPL uses the "global" context as it's "this" (you can test that with global === this).

However, regular modules run in their own separate closure. So you can imagine it being something like this:

function (module, exports, global) {
  // your module code
}

So when you define a var in your and execute it as a script, you're really just defining it inside of a function closure. But in the REPL, you're defining the var at the global level.

like image 98
TooTallNate Avatar answered Oct 29 '22 19:10

TooTallNate