鍍金池/ 問答/HTML/ 將自調(diào)用函數(shù)中的構(gòu)造函數(shù)暴露在全局中,算閉包嗎

將自調(diào)用函數(shù)中的構(gòu)造函數(shù)暴露在全局中,算閉包嗎

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

    1,這種形式算閉包嗎 ?
    2,自調(diào)用函數(shù)算定義在全局中還是在哪呢?
回答
編輯回答
櫻花霓
詞法作用域中使用的域,是變量在代碼中聲明的位置所決定的。嵌套的函數(shù)可以訪問在其外部聲明的變量。
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();

建議系統(tǒng)地了解一下

2017年12月15日 20:19
編輯回答
真難過
  1. 不算閉包,只是給全局作用域上的window添加了屬性而已。

    var s=new window.Student();
  2. 沒看懂問題
2018年6月24日 10:01
編輯回答
帥到炸

1.

function() {
    function Student() {
    }
}
// 這部分滿足閉包的其中一個(gè)條件:函數(shù)中包含內(nèi)部函數(shù)。
// 但是,在Student函數(shù)內(nèi)部沒有引用外部函數(shù)的變量。
// 所以在外部函數(shù)執(zhí)行的時(shí)候,并沒有形成閉包。

閉包參見下面例子:

// 這個(gè)函數(shù)就有形成閉包的潛力,因?yàn)閮?nèi)部函數(shù)中引用了外部函數(shù)的變量
// 但是如果這個(gè)函數(shù)不執(zhí)行都是扯淡。
function outer() {
    const a = 1;
    
    return function() {
        return a;
    }
}

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

2.自調(diào)用函數(shù)定義在全局函數(shù)還是哪里,如果不知道的話,可以代碼測(cè)試一下,比如下面這種:

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

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

如果是在全局函數(shù)中,上面test就可以訪問到了,結(jié)果是報(bào)錯(cuò)了。
所以,答案也有了,自調(diào)用函數(shù)定義在()模塊中

2017年9月18日 14:26