var:重新宣告會覆蓋前面的值,function與if作用域又不同
let:區域變數,作用範圍比var還小,不能在同個scope使用let關鍵字再次宣告同名稱的變數,否則會報錯,但var可以
const:用來定義常數,只能在定義時設定初值,之後就不能改變,但可以在定義時計算初值。如果把一個物件宣告成const,但此物件的屬性還是可以更改,因為物件只是參考
沒用關鍵字宣告變數也可以,會變成全域變數:
name = "123";
console.log(name);//印出123
console.log(global);
以下為印出global的部分內容:
...
Buffer:
{ [Function: Buffer]
poolSize: 8192,
from: [Function],
alloc: [Function],
allocUnsafe: [Function],
allocUnsafeSlow: [Function],
isBuffer: [Function: isBuffer],
compare: [Function: compare],
isEncoding: [Function],
concat: [Function],
byteLength: [Function: byteLength],
[Symbol(node.isEncoding)]: [Function] },
clearImmediate: [Function],
clearInterval: [Function],
clearTimeout: [Function],
setImmediate: { [Function: setImmediate] [Symbol(util.promisify.custom)]: [Function] },
setInterval: [Function],
setTimeout: { [Function: setTimeout] [Symbol(util.promisify.custom)]: [Function] },
name: '123' }
沒用關鍵字宣告它會把變數放到global物件底下function外面看得到function內的var變數嗎?
nameA = "Adora";
nameB = "Bella";
function showName() {
var nameC = "Ingrid";
console.log(nameC);
console.log(nameA);
}
showName();
console.log(nameC);//會錯,外面看不到function內的var變數
console.log(nameB);
執行結果:
Ingrid
Adora
/Users/xanxus/Desktop/nodejsHttpTest/momentTest.js:17
console.log(nameC);//會錯,外面看不到function內的var變數
^
ReferenceError: nameC is not defined
at Object. (/Users/xanxus/Desktop/nodejsHttpTest/momentTest.js:17:13)
at Module._compile (module.js:652:30)
at Object.Module._extensions..js (module.js:663:10)
at Module.load (module.js:565:32)
at tryModuleLoad (module.js:505:12)
at Function.Module._load (module.js:497:3)
at Function.Module.runMain (module.js:693:10)
at startup (bootstrap_node.js:188:16)
at bootstrap_node.js:609:3
var變數在function外就存取不到了,而未使用關鍵字宣告的全域變數在function內還是存取得到。function存取得到外面的var變數嗎?
var nameA = "Adora";
var nameB = "Bella";
function showName() {
var nameC = "Ingrid";
console.log(nameC);
console.log(nameA);//印出Adora
}
showName();
console.log(nameB);
看來是可以的。但偶爾還是有例外,請看以下連結,提升 (Hoisting)的部分:https://ithelp.ithome.com.tw/articles/10191549
那if, else, for, while裡的var變數,外面存取得到嗎?
// 宣告變數 a
var a = 10;
if(true){
// 在if(block scope)中宣告變數 b
var b = 20;
}
console.log(a);//印出10
console.log(b);//印出20
可以唷!所以var在if, else, for, while和function宣告的時候,作用域又不一樣。此例可看出外面還是可以存取得到if裡面的var變數。
在nod.js與一般網頁中的全域物件global與window
根據這個連結 https://ithelp.ithome.com.tw/articles/10191549 中描述,以var宣告的變數在網頁中用全域物件window來存取,可以取得到值
我秉著實驗精神一樣在node.js中的程式以var宣告一個變數a=10
以為console.log(global.a);會印出10,結果卻輸出undefined
這問題先放著,有找到網路上類似的問題:
沒有留言:
張貼留言