先進のJavaScriptシリーズ-パート4.1:グローバル、機能とブロック範囲
スコープとは
In simple terms, Scope can be defined as the space in which variables and statements are accessible.
or
Scope determines the accessibility of variables, objects, and functions from different parts of the code.
例
var x = 2
function myFunc(){
console.log(x)
}
myfunc関数は変数にアクセスすることができますx
したがって、私たちはx
はmyfuncの範囲にある.3スコープの種類:
クレジット
1 .グローバルスコープ
var
, let
or const
, グローバルスコープで宣言された変数は同様に動作します.例
var x = 2
function myFunc(){
console.log(x)
}
ここで変数x
グローバルスコープで宣言され、プログラム全体で使用可能です.var
, let
or const
キーワード、常にグローバルスコープで宣言されます.例
function myFunc(){
x = 1
}
console.log(x)
ここでコードは出力1
変数からx
グローバルスコープで宣言されます.2 .関数/ローカルスコープ
var
, let
and const
関数スコープで同様に動作します.例
function myFunc(){
let x = 1
console.log(x)
}
ここで変数x
この関数は、関数の中からのみアクセス可能です.ブロックスコープ
let
and const
ES 6で導入されたのはブロックスコープです.例
var x = 1
if(x){
var y = 2
let z = 3
console.log("hello world")
}
console.log(y)
console.log(z)
出力
2
Uncaught ReferenceError: z is not defined
ここで変数y
外部からアクセスできませんif block
変数はlet
を使って宣言された変数var
でない.語彙対ダイナミックスコープ
Lexical scoping refers to the variables in the location of a function's definition, whereas dynamic scoping refers to the variables in the location of a function's invocation.
例
コード
function a() {
console.log(i);
}
function b() {
var i = 1;
a();
}
var i = 0;
b();
解説
We have two function,
a
andb
.a
logs out the value ofi
which is set globally to0
.b
sets its value to1
, and callsa
. If we callb
, it will log out0
. This is because — whilea
doesn't have a variable calledi
—a
has access to the enclosing scope where the function is defined. And in the global scope, we have ani
which is set to0
. This is called lexical scoping.In dynamic scoping, the value of
i
will be1
. This is because instead of looking at where the function is defined, it looks at where it is called from. It sees from the call stack that it has been called fromb
, which sets the value ofi
to be1
.
私とつながってください
付録
リファレンス
Reference
この問題について(先進のJavaScriptシリーズ-パート4.1:グローバル、機能とブロック範囲), 我々は、より多くの情報をここで見つけました https://dev.to/pranav016/advanced-javascript-series-part-41-global-function-and-block-scope-lexical-vs-dynamic-scoping-20pgテキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol