Scope is the set of variables, objects, and functions you have access to.
包含 變量,對象和方法
Function Scope Variables 函數(shù)局部作用域變量
在方法內部定義的變量许饿,屬于方法的局部變量阳欲,只能在方法內部訪問。
function f() {
var foo = 123;
console.log(foo);
}
f(); // 123
Global Scope Variables 全局作用域變量
在方法外部定義的變量陋率,屬于全局變量球化,在當面頁面中都可以訪問。
var foo = 123;
function f() {
console.log(foo);
}
f(); // 123
Global and local variables with the same name are different variables. Modifying one, does not modify the other.
兩個變量即使名字相同瓦糟,但如果作用域不同筒愚,也屬于不同的兩個變量。修改只對當前作用域的變量有效菩浙。
Automatically Global 自動全局變量
Variables created without the keyword var, are always global, even if they are created inside a function.
不使用 var 關鍵字創(chuàng)建的變量巢掺,默認為全局變量,即使是在方法內部創(chuàng)建芍耘。
function f() {
foo1 = 123; // 對未聲明的變量賦值址遇,該變量自動成為全局變量
}
f();
foo2 = 456; // 對未聲明的變量賦值熄阻,該變量自動成為全局變量
console.log(foo1); // 123斋竞,foo1 為全局變量
console.log(foo2); // 456,foo2 為全局變量
use strict
ES5 標準中提出秃殉。
"use strict"; Defines that JavaScript code should be executed in "strict mode".
使得 JavaScript 代碼在嚴格模式下執(zhí)行坝初,例如不能使用未聲明的變量。
'use strict';
foo = 123;
console.log(foo); // ReferenceError: foo is not defined
Block Scope Variables 代碼塊作用域變量
參見 JavaScript ES6 var VS let 區(qū)別
var foo = 5;
for(var i = 1; i <= 3; i++) {
var foo = i; // Function Scope
}
console.log(foo); // 3
var foo = 5;
for(var i = 1; i <= 3; i++) {
let foo = i; // Block Scope
}
console.log(foo); // 5
Global Variables in HTML
全局范圍是當前 Java Script 的運行環(huán)境钾军,即 window
對象鳄袍,所有全局變量都屬于 window
對象。
var foo = 123;
console.log(window.foo);
Variable Lifetime 變量生命周期
- 全局作用域變量存在于整個應用程序(your window / your web page)
- 函數(shù)局部作用域變量生命周期較短吏恭,在函數(shù)調用時創(chuàng)建拗小,函數(shù)調用結束時刪除
一些示例:
var foo = 123;
function f() {
var foo = 321;
console.log(foo); // 先在當前 function scope 去找 foo,如果找不到樱哼,再去上一層 global scope 去找 foo
}
f(); // 321
var foo = 123;
function f() {
var foo = 321;
}
f();
console.log(foo); // 123哀九,在當前 global scope 去找 foo
Hoisting
Hoisting is JavaScript's default behavior of moving declarations to the top.
自動將變量的聲明移動到頭部,即變量可以先使用搅幅,再聲明阅束。
例如,如下的兩段代碼等價:
'use strict';
foo = 123;
console.log(foo); // 123
var foo; // 自動將變量的聲明移動到頭部
'use strict';
var foo;
foo = 123;
console.log(foo); // 123
Hoisting 也適用于方法茄唐,即方法可以先使用息裸,再聲明。 例如:
'use strict';
f(); // 123
function f() {
console.log(123);
}
JavaScript Initializations are Not Hoisted 初始化不能被 Hoisted
例如:
'use strict';
console.log(foo); // undefined
var foo = 123; // 初始化不能被 Hoisted
函數(shù)嵌套的 Scope
In JavaScript, all functions have access to the scope "above" them.
所有的函數(shù)都能訪問上一層的 Scope。
例如:
function f1() {
var i = 0;
function f2() {
i = 1; // 函數(shù)都能訪問上一層的 Scope
}
f2();
console.log(i);
}
f1(); // 1