zachberry
zachberry

Reputation: 97

How do named function definitions work inside non-global scopes in Javascript?

If the following code is executed is G defined anywhere?

function F() { function G() {} } f = new F();

I get that F is now available as F or window.F (assuming browser context), but I'm not sure if it's possible to have a named function definition inside a non-global scope (such as F's scope when invoked via new).

Alternatively, I can hold on to a reference to it, via

function F() { function G() {} window.theG = G; } f = new F();

and then console.log(window.theG) returns function G() (in Chrome DevTools). So G exists, and we have a reference to it, but is there any other way I can access G?

Upvotes: 1

Views: 36

Answers (2)

GPicazo
GPicazo

Reputation: 6676

In the first example that you provided G would be a private variable of F. Because it only lives in the context of F, once F is executed, G is disposed. If you want to retain a reference to it, you can either assign it to the global scope as you did in the 2nd example of set it as a property of F like so:

function F() {
    this.G = function () {}
}

and now you can access it like so:

var f = new F();
f.G();

Upvotes: 2

Quentin
Quentin

Reputation: 943510

Function declarations create a variable matching the function name in the current scope.

When F is called, a local variable called G is created. Unless you copy its value somewhere (e.g. with window.theG although this.theG would be a more common pattern) the function will finish executing, there will be no references left to it and it will be garbage collected.

i.e. it behaves just like any other local variable with a value. There isn't anything special about functions in that regard.

Upvotes: 4

Related Questions