2

In the browsers execution environment when you define a function, that function is a member of the window object. For example:

function myFunc() {
    console.log( 'hello' );
}

console.log( window.myFunc );   // valid

In NodeJS, we don't have a window object, be we do have a global and a module object. However, when you define a function the same way in the NodeJS execution environment, this function is not part of global object or the module object.

function myFunc() {
    console.log( 'hello' );
}

console.log( global.myFunc );   // undefined
console.log( module.myFunc );   // undefined

So which object is myFunc a member of?

Zachery
  • 37
  • 2

1 Answers1

0

Functions in Javascript are not automatically a member of any particular object. If you want them to be, then you have to assign them that way.

It does so happen that in a browser, a function defined in the global scope will be attached to the window object, but that is a nuance of the browser implementation, not of Javascript itself.

And, in fact the language is moving away form this since newer things like class definitions in the top level scope are not attached to the window object.

In node.js, your default top level scope is the module scope and functions defined there are not automatically attached to any object. If you want a function to be global, then you have to assign it to the global object.

Though, please keep in mind that node.js has a modular architecture precisely so that you do NOT make functions you define global. Instead, you export them from a module and have any other module that wants to use them import or require() your module to get access to the function. In this way, all dependencies are explicitly declared in the code rather than implicitly defined in the code through globals.

So, in node.js if you want a function to be attached to an object, you have to explicitly put it on the object as a named property. Javascript does not provide a means in the language to iterate all objects/functions defined within a scope.

jfriend00
  • 683,504
  • 96
  • 985
  • 979