鍍金池/ 問答/HTML/ JS閉包相關(guān) 閉包內(nèi)創(chuàng)建的對象如何獲???

JS閉包相關(guān) 閉包內(nèi)創(chuàng)建的對象如何獲?。?/h1>

我用一個全局對象,新建其一個屬性來引用閉包內(nèi)創(chuàng)建的對象

function fun(){
    return function(){
        var obj1={
            a:1,
            b:2
        };
        obj2.item=obj1;
    }
}
var obj2={};
fun();
console.log(obj2.item.a);

結(jié)果顯示 Cannot read property 'a' of undefined
請問這樣獲取閉包內(nèi)對象的方式錯在哪?閉包內(nèi)對象會自動釋放嗎?如果會自動釋放,為什么?謝謝


第二個問題

var testButton1=document.getElementById("testButton1");
var testButton2=document.getElementById("testButton2");
testButton1.onclick=fun_1;
testButton2.onclick=fun_2;

function fun_1(){
    
    var obj1={
        a:1,
        b:2
    };
    obj2.item=obj1;
    
}

function fun_2(){
    console.log(obj2.item.a);
}
var obj2={};

結(jié)果也顯示Cannot read property 'a' of undefined 是為什么

回答
編輯回答
舊時光

你執(zhí)行fun()的時候返回的是一個函數(shù),這個函數(shù)還沒有執(zhí)行,
圖片描述

所以要這樣寫:

function fun(){
    return function(){
        var obj1={
            a:1,
            b:2
        };
        obj2.item=obj1;
    }
}
var obj2={};
fun()();
console.log(obj2.item.a);

倒數(shù)第二段:fun() 改為 fun()()
2017年10月25日 17:13
編輯回答
愚念

匿名函數(shù)沒有調(diào)用,局部變量調(diào)用后失效,閉包可以保持變量在內(nèi)存中不被回收

       function fun(){
    return  (function(){
        var obj1={
            a:1,
            b:2
        };
        obj2.item=obj1;
    })();
}

或者

       function fun(){
    return  function(){
        var obj1={
            a:1,
            b:2
        };
        obj2.item=obj1;
    };
}
fun()();
2018年8月23日 08:14
編輯回答
愛礙唉

返回值是函數(shù),fun()只是調(diào)用外部函數(shù),里面的函數(shù)并沒有執(zhí)行,將fun()改為fun()()即可。

2018年1月8日 13:32
編輯回答
使勁操

這里有js閉包的幾個例子,可以參考下http://www.aazzp.com/2017/11/...

2017年7月29日 18:29