为什么单独依赖范围链并避免在Javascript中显式引用头对象是有益的? [英] Why is it beneficial to rely on the scope chain alone and avoid explicitly referencing the head object in Javascript?

查看:62
本文介绍了为什么单独依赖范围链并避免在Javascript中显式引用头对象是有益的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在读Cody Lindley的这本书Javascript Enlightenment。在第82页,他指出:显式(例如window.alert()vs alert())在性能方面要花费更多。如果单独依赖范围链并避免显式引用头对象,则速度会更快你知道你想要的属性包含在全局范围内。

I've been reading this book "Javascript Enlightenment" by Cody Lindley. On page 82 he states: "Being explicit (e.g. window.alert() v.s. alert()) costs a little bit more with regards to performance. It's faster if you rely on the scope chain alone and avoid explicitly referencing the head object even if you know the property you want is contained in the global scope."

我有点好奇为什么会这样。我认为这是相反的,因为Javascript解释器可以跳过检查范围并直接找到它。我只是没有看到没有指定某些东西的确切地址是多么有益。

I am kind of curious why this is. I would think that it would be the opposite, because the Javascript interpreter could just skip checking the scope and find it directly. I just don't see how it is beneficial to not specify the exact address of something.

我的意思是,我知道每次我想要使用全局范围内的东西时我都不想输入window.whatever()而且我认为它是很好,没有指定更快。只是不确定原因。

I mean, I know I am not going to want to type window.whatever() every time I want to use something contained in the global scope and I think it is great that it is faster to not specify. Just not sure why.

只是其中一个想知道事情。

Just one of those "want to know" things.

推荐答案

解释器总是必须使用范围链。当您编写 window.alert()时,它必须沿着范围链向上走,以找到窗口的值 - 您可能有一个名为 window 的局部变量,它会遮蔽头部中的那个变量,所以它不能假设这是全局对象。

The interpreter always has to use the scope chain. When you write window.alert() it has to walk its way up the scope chain to find the value of window -- you might have a local variable named window that shadows the one in the head, so it can't assume this is the global object.

如果JavaScript有一个语法来明确表示顶级上下文,那就会更快。但事实并非如此。

If JavaScript had a syntax to explicitly denote the top-level context, that would be faster. But it doesn't.

这篇关于为什么单独依赖范围链并避免在Javascript中显式引用头对象是有益的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆