gpt4 book ai didi

javascript - JavaScript 中的作用域链是什么?

转载 作者:行者123 更新时间:2023-12-03 04:00:09 27 4
gpt4 key购买 nike

when I used below code:

function a(){
var q = 1;
function b(){
console.log(q);
}
b();
}

var q= 2;
a();

It gives me output as 1. But when I used below code:

function b(){
console.log(q);
}

function a(){
var q = 1;
b();
}

q= 2;
a();

output is 2. and also when I used below code:

function a(){
function b(){
console.log(q);
}
b();
}

var q= 2;
a();

Again I got Output as 2. I know it is something related to scope chain as I searched in google but didn't understood completely.

最佳答案

作用域链只是声明标识符的位置,搜索该位置以解析标识符的值。

区分何处声明某项内容与何时声明某项内容非常重要。仅仅因为您在使用 q 的函数调用之前声明 q 并不意味着这就是将要使用的 q - 可以是多个 q 变量,每个变量都有自己的作用域。

在我们查看您的示例之前,请想象一下这种情况。你在一个大房间里,房间被分成足够容纳两个 worker 的小隔间。您和您的同事“乔”共用一个隔间(因为您在那里,所以这是您的本地范围,并且您与乔共享)。如果您和乔同时坐在共用的隔间里,并且您想与乔交谈,您只需说“嘿乔”,乔就会立即做出回应。但是,如果乔起身去办公室饮水机取水怎么办?如果您随后说“嘿乔”,则不会在您的小隔间范围内找到他,因此您必须将搜索范围扩大到整个办公室(包含您的隔间所在范围的更高范围)。但是,通过将搜索范围扩大到下一个更高的范围(沿着范围链向上),您最终会找到乔。现在想象一下同一楼层的两个办公室共享饮水机。您不会在您的小隔间中找到乔,他也不会在您的办公室中,因此您必须再次扩大搜索范围以包括您可见的其他范围(隔壁的办公室)。

还在我身边吗?现在,有一个问题......如果每个位置都有不同的“Joe's”,而您想要与之交谈的 Joe 在另一个办公室怎么办?当你说“嘿乔!”时,最接近的人会回复,但这可能不是你心目中的乔。这就是您的 q 变量所发生的情况。您在不同的作用域级别声明了多个声明,而您期望的声明并不是最接近您调用它的作用域的声明。

function a(){
// q is declared in this scope and this is the next highest scope to where it is
// used for the console.log, so 1 is the output
var q = 1;
function b(){
// q isn't declared in this function's scope, so the next higher scope
// needs to be checked.
console.log(q);
}
b();
}

// Even though this code runs just before the function call,
// this is creating a different "q" variable in the higest scope
// -- the global scope. When the function runs, it won't need
// to search all the way up to this level to find a declaration
// for q, so 2 isn't what is outputted
var q= 2;

// Now, run the function
a();

function b(){
// Here, there is no q in this local scope,
// so again, the next highest scope is searched.
// Since this is NOT a nested function, the next highest
// scope is the global scope and the q in that scope is found
// producing 2 as output
console.log(q);
}

function a(){
// Create a local q variable that only is accessible from here
var q = 1;

// Invoke the b function
b();
}

// Global q is being set
q = 2;

// Invoke the a function
a();

function a(){
// There is no q in this scope, so the next highest scope (the global scope)
// is checked.
function b(){
// There is no q in this scope, so the scope of a is checked
console.log(q);
}
b();
}

// Not only is this the Global q, but it's the only q declared
var q= 2;
a();

关于javascript - JavaScript 中的作用域链是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44748842/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com