Day 8:var 掰掰 —— ES6 更嚴謹安全的 let 和 const
Last updated
Was this helpful?
Was this helpful?
{
let x = 2;
{
console.log(x); // 2
}
console.log(x); // 2
}
console.log(x); // ReferenceError: x is not defined{
let x = 10;
let x = 2; // SyntaxError: Identifier 'x' has already been declared
}{
var x = 10;
let x = 2; // SyntaxError: Identifier 'x' has already been declared
}{
let x = 2;
{
let x = 10;
console.log(x); // 10
}
console.log(x); // 2
}function myFunc(){
var n1 = "Stephen Chow";
console.log("myFunc(): n1=", n1);
console.log("myFunc(): n2=", n2);
}
var n1 = "Tom Cruise";
var n2 = "Meryl Streep";
myFunc();
console.log("Global: n1=", n1);myFunc(): n1= Stephen Chow
myFunc(): n2= Meryl Streep
Global: n1= Tom Cruisefunction myFunc(){
console.log("myFunc(): n1=", n1);
console.log("myFunc(): this.n1=", this.n1);
console.log("myFunc(): window.n1=", window.n1);
}
var n1 = "OneJar";
myFunc();
console.log("Main: n1=", n1);myFunc(): n1= OneJar
myFunc(): this.n1= OneJar
myFunc(): window.n1= OneJar
Main: n1= OneJarfunction myFunc(){
console.log("myFunc(): n1=", n1);
console.log("myFunc(): this.n1=", this.n1);
console.log("myFunc(): window.n1=", window.n1);
}
let n1 = "OneJar";
myFunc();
console.log("Main: n1=", n1);myFunc(): n1= OneJar
myFunc(): this.n1= undefined
myFunc(): window.n1= undefined
Main: n1= OneJarfunction MAIN(){
function myFunc(){
console.log("myFunc(): n1=", n1);
console.log("myFunc(): this.n1=", this.n1);
console.log("myFunc(): window.n1=", window.n1);
}
let n1 = "OneJar";
myFunc();
console.log("Main: n1=", n1);
}{
const x = 10;
}
console.log(x); // ReferenceError: x is not definedvar x = 10;
const x = 10; // SyntaxError: Identifier 'x' has already been declaredconst x = 10;const x; // SyntaxError: Missing initializer in const declarationconst x = 10;
x = 20; // TypeError: Assignment to constant variable.