JavaScript 作用域链
我正在尝试优化我的程序。我想我了解闭包的基础知识。不过,我对作用域链感到困惑。
我知道通常您需要较低的范围(以快速访问变量)。
假设我有以下对象:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
有很多优化 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 globalwindow
object, the instance that the function was called on, or the first parameter passed tocall
orapply
.The
this
object will refer to a normal Javascript object; its properties have no scope.首先,您是否分析过您的应用程序,并且您知道此代码是瓶颈吗?
如果您的应用程序 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.