// let result1 = buildName("Bob"); // error, too few parameters // let result2 = buildName("Bob", "Adams", "Sr."); // error, too many parameters let result3 = buildName("Bob", "Adams"); // ah, just right
functionbuildName(firstName: string, lastName?: string){ if (lastName){ return firstName + " " + lastName; }else{ return firstName; } } let result1 = buildName("Bob"); // works correctly now // let result2 = buildName("Bob", "Adams", "Sr."); // error, too many parameters let result3 = buildName("Bob", "Adams"); // ah, just right
let res1 = buildName("Bob"); // works correctly now, returns "Bob Smith" let res2 = buildName("Bob", undefined); // still works, also returns "Bob Smith" // let res3 = buildName("Bob", "Adams", "Sr."); // error, too many parameters let res4 = buildName("Bob", "Adams"); // ah, just right
let cardPicker = deck.createCardPicker(); let pickedCard = cardPicker();
alert("card: " + pickedCard.card + " of " + pickedCard.suit);
上述範例是可以編譯的,但是在執行的時候會有錯誤
因為在執行照 createCadrPicker 的時候會找不到 suits 這個 Function 因為這是 this的作用域的問題
因為對 Javascript 來說 Function 也是物件,所以在上述範例中的 createCadrPicker 中的 this 是指這個 createCadrPicker Function 本身,但是這個 Function 並沒有 suits 這個屬性,所以他會找到 undefeind 在後面 this.suits[pickedSuit] 的時候因為 undefined 在 Javascript 並不是物件,所以就會造成這個錯誤
所以我們可以把這個範例做一些修改
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
let deck = { suits: ["hearts", "spades", "clubs", "diamonds"], cards: Array(52), createCardPicker: function() { // NOTE: the line below is now an arrow function, allowing us to capture 'this' right here return() => { let pickedCard = Math.floor(Math.random() * 52); let pickedSuit = Math.floor(pickedCard / 13);
classHandler { info: string; onClickBad(this: Handler, e: Event) { // oops, used this here. using this callback would crash at runtime this.info = e.message; } } let h = newHandler(); uiElement.addClickListener(h.onClickBad); // error!