// 在 ES5 中,你使用 var 宣告變數,且可以賦予新值:vartext='hello';text='world';// 而 ES6 提供你兩個新功能:// 1. 使用 let 宣告「區域變數」// 2. 使用 const 宣告「常數」// 範例如下:lettext='hello';constTEXT='hello';text='world';TEXT='world';// 發生錯誤:Uncaught SyntaxError: "TEXT" is read-only// 上例中,因為 const 一旦宣告後,就無法重新賦值,所以發生錯誤。// 因此 cosnt 通常用在宣告常數,那麼 let 和 var 的差別是什麼呢?// 見下方範例:varvText='vText';letlText='lText';if(true){varvText='vText2';letlText='lText2';console.log(vText);// vText2console.log(lText);// lText2}console.log(vText);// vText2console.log(lText);// lText// It's magic!// 上例讓我們得知:// 在 if 區塊中使用 let 宣告的變數,只能在 if 區塊內使用;// 而 var 卻無限制,這就是 let 和 var 的差別。// 再看一個例子:if(true){lettext='hello';}console.log(text);// 發生錯誤:Uncaught ReferenceError: text is not defined
:小提醒,為了增加程式閱讀性和降低出錯率,建議你培養好習慣 - 宣告變數盡量使用 let 取代 var,常數用 const:)
classPerson{// 1. 使用 class 建立類別constructor(name){// 2. 使用 constructor 定義建構子this.name=name;}speak(){console.log('My name is '+this.name);}}constjason=newPerson('Jason Chung');jason.speak();// My name is Jason ChungclassMenextendsPerson{// 3. 使用 extends 繼承類別speak(){super.speak();// 4. 使用 super 呼叫父類別方法console.log('I\'m a man');}}constandy=newMen('Andy Lin');andy.speak();// My name is Andy Lin// I'm a man
17 comments