关于 Javascript 作用域链

发布于 2024-12-22 15:33:26 字数 236 浏览 4 评论 0原文

它们之间有什么区别?
①函数的作用域-->②[[scope]]---->③scope

var scope = 'window';
var someFunction = function(){
    something go here....
}

someFunction的作用域
someFunction[[scope]]
窗口作用域
是这样吗?

what's the difference between them ?
①function's scope-->②[[scope]]---->③scope

var scope = 'window';
var someFunction = function(){
    something go here....
}

someFunction's scope
someFunction[[scope]]
window scope
is that right?

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

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

发布评论

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

评论(1

终难愈 2024-12-29 15:33:26

如果你想了解作用域链,你应该阅读 Richard Cornford 关于 JavaScript 闭包 的文章,特别是关于标识符解析、执行上下文和范围的部分链

简而言之,作用域链从变量/激活对象行进到变量/激活对象,并在全局对象处停止(因为全局对象实际上是全局执行上下文的激活/变量对象)。

因此,在这种情况下:

var fred;

function foo() {
    alert(fred);
}

标识符 fred 被设为全局变量/激活对象的属性(在全局代码的情况下是全局对象本身)。当调用foo()时,会创建一个新的变量/激活对象,其作用域链包含全局对象。标识符fred首先在内部变量对象上解析,并且由于在那里找不到它,因此搜索链上的下一个对象(全局对象)。

类似地:

function foo() {
    function bar() {
        alert(fred);
    }
    bar();
}

因此,当调用 foo() 时,它会调用 bar(),现在 fred 首先针对 bar 的变量对象进行解析,然后是 foo 的,然后是全局对象。

一旦理解了执行上下文,您也会意识到为什么将this的值称为“上下文”会产生误导。

If you want to understand the scope chain, you should read Richard Cornford's article on JavaScript Closures, particularly the part on Identifier Resolution, Execution Contexts and scope chains.

Briefly, the scope chain travels from variable/activation object to variable/activation object, stopping with the global object (since the global object is effectively the activation/variable object for the global execution context).

So in the case of:

var fred;

function foo() {
    alert(fred);
}

The identifier fred is made a property of the global variable/activation object (which in the case of global code is the global objet itself). When foo() is called, a new variable/activation object is created with a scope chain that includes the global object. The identifier fred is first resolved on the internal variable object, and since it won't be found there, the next object on the chain (the global object) is searched.

Similarly for:

function foo() {
    function bar() {
        alert(fred);
    }
    bar();
}

So when foo() is called, it then calls bar(), and now fred is resolved against firstly bar's variable object, then foo's, then the global object.

Once you understand execution context, you will also realise why calling the value of this "context" is misleading.

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