ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

javascript – 为什么无法在闭包中的私有函数中直接访问此属性?

2019-09-01 13:33:41  阅读:285  来源: 互联网

标签:javascript closures language-design


在我自己对A JavaScript VM that interprets code written in JSON的回答中,我说过无法在“私有”函数中访问JavaScript闭包的“公共”属性.

该帖子中给出的例子是

function anobject(){
    var privatefunction = function(){
        //publicfunction(); //wrong; you have no access to it
        console.log(this); //refer to the global object, not the object creating
    };
    this.publicfunction = function(){
        console.log(this); //refer to the object creating
    }
}

我认为原因是一些向后兼容性问题,privatefunction必须属于全局对象.因此,public函数只是一个分配给它的属性的匿名函数.这解释了为什么调用publicfunction会失败,因为它需要首先引用它.

但是,以下修复仍然无法正常工作:

function anobject(){
    var privatefunction = function(){
        //publicfunction(); //wrong; you have no access to it
        console.log(this); //refer to the object creating
    }.bind(this);
    this.publicfunction = function(){
        console.log(this); //refer to the object creating
    }
}

当我明确指出privatefunction应该与创建对象绑定时,调用publicfunction应该可以工作,但事实并非如此.我必须做以下事情:

function anobject(){
    var privatefunction = function(){
        this.publicfunction();
        console.log(this); //refer to the object creating
    }.bind(this);
    this.publicfunction = function(){
        console.log(this); //refer to the object creating
    }
}

另一种解决方法(我使用的方式)如下:

function anobject(){
    var privatefunction = function(){
        publicfunction();
        console.log(this); //refer to the object creating
    };
    var publicfunction = function(){
        console.log(this); //refer to the object creating
    }
    this.publicfunction = publicfunction;
}

现在是问题的一部分.这种行为背后的原因是什么?如果没有明确的规范,禁止访问这些属性,它试图避免什么?

更新:问题的主要部分是:当解释器在作用域链中找不到名称时,为什么不应该查看这些属性?

解决方法:

这里的问题是引用这是由函数/方法的调用者决定的,例如:

function anobject(){
    // here "this" is the object
    var privatefunction = function(){
        // here "this" is the object **that called privatefunction()**
    };
    this.publicfunction = function(){
        // this method will always be called by the object, so "this" is the object
    }
}

为了实现你想要的你也可以试试这个:

function anobject(){
    var that = this;
    var privatefunction = function(){
        [do what you like using "that"]
    };
    this.publicfunction = function(){
        [here you can use "this" directly, or "that"]
    }
}

另请参阅javascript范围如何工作,这里是What is the scope of variables in JavaScript?和网络上的.

标签:javascript,closures,language-design
来源: https://codeday.me/bug/20190901/1783845.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有