账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    JS闭包相关 闭包内创建的对象如何获取?
    33
    0

    我用一个全局对象,新建其一个属性来引用闭包内创建的对象

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

    结果显示 Cannot read property 'a' of undefined
    请问这样获取闭包内对象的方式错在哪?闭包内对象会自动释放吗?如果会自动释放,为什么?谢谢


    第二个问题

    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={};
    

    结果也显示Cannot read property 'a' of undefined 是为什么

    0
    打赏
    收藏
    点击回答
    您的回答被采纳后将获得:提问者悬赏的 10 元积分
        全部回答
    • 0
    更多回答
    扫一扫访问手机版
    • 回到顶部
    • 回到顶部