JavaScript 作用域链

发布于 2024-08-24 13:39:40 字数 776 浏览 4 评论 0原文

我正在尝试优化我的程序。我想我了解闭包的基础知识。不过,我对作用域链感到困惑。

我知道通常您需要较低的范围(以快速访问变量)。

假设我有以下对象:

var my_object = (function(){

        //private variables
        var a_private = 0;

    return{ //public
             //public variables
             a_public : 1,

             //public methods
             some_public : function(){
                  debugger;
                  alert(this.a_public);
                  alert(a_private);
             };
        };
})();

我的理解是,如果我在 some_public 方法中,我可以比公共变量更快地访问私有变量。这是正确的吗?

我的困惑来自于 this 的范围级别。

当代码在调试器处停止时,firebug 会显示 this 关键字内的公共变量。 this 词不在范围级别内。

访问这个的速度有多快?现在,我将任何 this.properties 存储为另一个局部变量,以避免多次访问它。

非常感谢!

I am trying to optimize my program. I think I understand the basics of closure. I am confused about the scope chain though.

I know that in general you want a low scope (to access variables quickly).

Say I have the following object:

var my_object = (function(){

        //private variables
        var a_private = 0;

    return{ //public
             //public variables
             a_public : 1,

             //public methods
             some_public : function(){
                  debugger;
                  alert(this.a_public);
                  alert(a_private);
             };
        };
})();

My understanding is that if I am in the some_public method I can access the private variables faster than the public ones. Is this correct?

My confusion comes with the scope level of this.

When the code is stopped at debugger, firebug shows the public variable inside the this keyword. The this word is not inside a scope level.

How fast is accessing this? Right now I am storing any this.properties as another local variable to avoid accessing it multiple times.

Thanks very much!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

童话里做英雄 2024-08-31 13:39:40

有很多优化 Javascript 的好方法。

这不是其中之一。
搜索范围的成本为分钟

此外,您还误解了 this 关键字。
this 关键字是每个函数的隐式参数,该参数可以是全局 window 对象、调用该函数的实例,或者传递给 代码>调用应用
this 对象将引用普通的 Javascript 对象;它的属性没有范围。

There are many good ways to optimize Javascript.

This is not one of them.
The cost of searching up the scope is minute.

In addition, you're misunderstanding the this keyword.
The this keyword is an implicit parameter to every function, which will either be the global window object, the instance that the function was called on, or the first parameter passed to call or apply.
The this object will refer to a normal Javascript object; its properties have no scope.

在风中等你 2024-08-31 13:39:40

首先,您是否分析过您的应用程序,并且您知道此代码是瓶颈吗?

如果您的应用程序 99.9% 的时间都花在做其他事情上,那么优化这一点就没有意义了。

First, have you profiled your application and do you know that this code is a bottleneck?

There's no point optimizing this if your applications spends 99.9% of its time doing something else.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文