简体   繁体   中英

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?

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 (eg 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.

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

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM