ฉันไม่สามารถเข้าใจได้ว่าทำไมตัวแปรต่าง ๆ จึงแปลกประหลาดเมื่อถูกประกาศภายในฟังก์ชั่น
ใน
firstฟังก์ชั่นฉันประกาศด้วยletตัวแปรbและcด้วยค่า10 :b = c = 10;ใน
secondฟังก์ชั่นที่ฉันแสดง:b + ", " + cและสิ่งนี้แสดงให้เห็นว่า:
10, 10ใน
firstฟังก์ชั่นฉันประกาศaด้วยค่า10 :let a = b = c = 10;แต่ใน
secondฟังก์ชั่นมันแสดงข้อผิดพลาด:ไม่พบตัวแปร:
aตอนนี้ใน
firstฟังก์ชันฉันประกาศdด้วยค่า20 :var d = 20;แต่ใน
secondฟังก์ชั่นจะแสดงข้อผิดพลาดเหมือนเดิม แต่มีตัวแปรd:ไม่พบตัวแปร:
d
ตัวอย่าง:
function first() {
let a = b = c = 10;
var d = 20;
second();
}
function second() {
console.log(b + ", " + c); //shows "10, 10"
try{ console.log(a); } // Rreference error
catch(e){ console.error(e.message) }
try{ console.log(d); } // Reference error
catch(e){ console.error(e.message) }
}
first()
Dim Apple, Banana, Pear As Fruitวิธีการและไม่Dim Apple / Dim Banana / Dim Pear As Fruit Dim Apple As Fruit / ...
bและcไม่ได้ขึ้นต้นด้วยvarคำหลักaและมีในท้องถิ่นเพื่อdfirst