Is it a closure to expose the constructor in the self-calling function to the global?

    (function(){
        function Student(){
            this.name="stu";
            this.age="18";
        }
        window.Student=Student;
    })();
    
    var s=new Student();
    console.dir(s);

    1 
    2
Mar.05,2021

1.

function() {
    function Student() {
    }
}
// :
// Student
// 

see the following example for closures:

// 
// 
function outer() {
    const a = 1;
    
    return function() {
        return a;
    }
}

// 
const getVal = outer();

2. The self-calling function is defined in a global function or somewhere. If you don't know, you can test it in code, such as the following:

(function test() {
    function Student(){
        this.name='stu';
        this.age='18';
    }
    window.Student=Student;
})();

var s=new Student();
console.dir(s);
test(); // Uncaught ReferenceError

if it is in a global function, the above test can be accessed, and the result is an error.
so, the answer is also available. The self-calling function is defined in the () module

.
  1. is not a closure, it just adds attributes to window on the global scope.

    var s=new window.Student();
  2. I don't understand the problem

The domain used in the
lexical scope is determined by where the variable is declared in the code. Nested functions can access variables declared outside them.
function init() {
    var name = "Mozilla"; // name is a local variable created by init
    function displayName() { // displayName() is the inner function, a closure
        alert (name); // displayName() uses variable declared in the parent function    
    }
    displayName();    
}
init();

it is recommended to systematically learn about

Menu