About JS Scope - 關於JS的作用域
Var, Let, Const Scope差別在哪裡?
-
定義
- 提升(Hoisting):是在 ECMAScript® 2015 Language Specification 裡面找不到的專有名詞。它是一種釐清 JaveScript 在執行階段內文如何運行的思路(尤其是在創建和執行階段)。然而,提升一詞可能會引起誤解:例如,提升看起來是單純地將變數和函式宣告,移動到程式的區塊頂端,然而並非如此。變數和函數的宣告會在編譯階段就被放入記憶體,但實際位置和程式碼中完全一樣。–轉MDN
-
Scope種類
- var - 屬於 Function scoped
- Global scope 無論寫在何處只要沒有var關鍵字則Hoisting,全局都可被訪問.
- Function scope 宣告使用var關鍵字,則會在當前function(object)可被訪問.
- const, let - 屬於 Block scoped
- Block scope 只要使用const,let 除了有var 特性外,在例如for, while, if else statement,都是獨立的block scope,ES6專屬,具體範例可以參考之前寫的Add five Button
- var - 屬於 Function scoped
(function createButton(){
// 把var改成let就實現了Block Scoped
for(let i=1;i<=5;i++){
var button = document.createElement('Button');
var body = document.getElementsByTagName('body')[0];
button.innerHTML = 'Button '+ i;
button.onclick = function(){
alert('This is Button: ' + i );
}
body.appendChild(button);
}
})()
- Question Scope and “self”
this.color = "red";
var myCar = {
color: "Blue",
logColor: function () {
var self = this;
console.log("In logColor - this.color: %s", this.color);
console.log("In logColor - self.color: %s", self.color);
(function () {
console.log("In logColor - this.color: %s", this.color);
console.log("In logColor - self.color: %s", self.color);
})();
}
}
myCar.logColor();
//In logColor - this.color: Blue
//In logColor - self.color: Blue
//In logColor - this.color: red
//In logColor - self.color: Blue
- 在inside of nested function(嵌套函數)使用this,此時引用會變成global scope,這是需要非常注意的
- Question Logout above your declare variable
- 當宣告變數後,因為Hoisting,此時num 尚未軾值
var num = 0;
(function logNum() {
console.log(num); //undefined
var num = 1;
})()
Published 16 Sep 2017