将自调用函数中的构造函数暴露在全局中,算闭包吗

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

    1,这种形式算闭包吗 ?
    2,自调用函数算定义在全局中还是在哪呢?
阅读 2.3k
3 个回答

1.

function() {
    function Student() {
    }
}
// 这部分满足闭包的其中一个条件:函数中包含内部函数。
// 但是,在Student函数内部没有引用外部函数的变量。
// 所以在外部函数执行的时候,并没有形成闭包。

闭包参见下面例子:

// 这个函数就有形成闭包的潜力,因为内部函数中引用了外部函数的变量
// 但是如果这个函数不执行都是扯淡。
function outer() {
    const a = 1;
    
    return function() {
        return a;
    }
}

// 闭包形成
const getVal = outer();

2.自调用函数定义在全局函数还是哪里,如果不知道的话,可以代码测试一下,比如下面这种:

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

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

如果是在全局函数中,上面test就可以访问到了,结果是报错了。
所以,答案也有了,自调用函数定义在()模块中

  1. 不算闭包,只是给全局作用域上的window添加了属性而已。

    var s=new window.Student();
  2. 没看懂问题
词法作用域中使用的域,是变量在代码中声明的位置所决定的。嵌套的函数可以访问在其外部声明的变量。
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();

建议系统地了解一下

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题