首頁  >  文章  >  web前端  >  JavaScript 的有趣之處以及 TypeScript 如何讓它變得更好

JavaScript 的有趣之處以及 TypeScript 如何讓它變得更好

Patricia Arquette
Patricia Arquette原創
2024-10-12 14:32:30486瀏覽

JavaScript’s Fun Twists and How TypeScript Makes It Better

JavaScript 是我們都喜歡的語言,對吧?它靈活、輕便,並且可以隨處運作。但儘管它很偉大,但說實話,它可能很奇怪。那種奇怪的感覺會讓你在看到一些不應該起作用的東西後質疑自己的理智。

在本文中,我們將探討 JavaScript 中的一些怪癖 - 那些在您最意想不到的時候讓您感到驚訝的行為。幸運的是,對於開發者來說,有一位閃亮盔甲的騎士,叫做TypeScript。我們在這裡向您展示如何透過使這些 JavaScript 的怪異更易於管理來避免您煩惱。


1. == vs === 大辯論

JavaScript 為我們提供了兩種相等性:== 或鬆散相等和 === 或嚴格相等。

console.log(0 == '0'); // true
console.log(0 === '0'); // false

等等,什麼?是的,JavaScript 使 0 和 '0' 在 == 時被視為相等,但在 === 時則不然。這是因為 == 在進行比較之前會進行 類型強制 或型別轉換。它試圖為您提供幫助,將該字串轉換為數字,但是這個幫助會導致錯誤。

想像一下在使用者輸入上使用 == 檢查數字。當類型不同導致難以追蹤的意外行為時,您可能會得到正確的結果。為什麼這很重要?因為 JavaScript 的強制型別通常會起作用,直到它破壞了一些重要的東西。

TypeScript 如何提供協助

TypeScript 已經強制執行開箱即用的型別安全。如果你比較兩個不同類型的東西,在你運行任何程式碼之前它就會對你大喊大叫:

let a: number = 0;
let b: string = '0';

console.log(a === b); // TypeScript Error: This comparison is invalid

將數字與字串進行比較時任何驚喜都消失了。 TypeScript 確保您始終比較蘋果和蘋果,或在這種情況下進行數字與數字的比較。


2. 神秘的 undefined 與 null

undefined 和 null 都表示什麼都沒有,但方式略有不同。 undefined 是 JavaScript 指派給尚未初始化的變數的值,而 null 用於當您有意指派空值時。它們各不相同,但又相似得令人困惑。

let foo;
console.log(foo); // undefined

let bar = null;
console.log(bar); // null

除非你很小心,否則你可能最終會檢查其中一個而不是另一個,這會導致一些令人困惑的錯誤。

if (foo == null) {
    console.log("This catches both undefined and null");
}

這可行,但如果您沒有清楚地區分兩者,可能會導致微妙的錯誤。

TypeScript 如何提供協助

TypeScript 鼓勵您明確且準確地判斷某些內容是否可以為 null 或未定義。它透過讓您明確處理這兩種情況來實現這一點,這樣您就可以確定發生了什麼:

let foo: number | undefined;
let bar: number | null = null;

// TypeScript will enforce these constraints
foo = null; // Error
bar = 5; // No problem!

使用 TypeScript,您可以決定允許哪些類型,這樣就不會意外地混合類型。這種嚴格性可以保護您免受忘記檢查 null 或未定義的錯誤的影響。


3. NaN(非數字)的奇怪情況

你遇過可怕的 NaN 嗎?它是 Not-a-Number, 的縮寫,當您嘗試執行沒有意義的數學運算時,它會彈出。

console.log(0 / 0);  // NaN
console.log("abc" - 5);  // NaN

這裡有一個問題:NaN 其實是數字類型。沒錯,不是數字是一個數字!

console.log(typeof NaN); // "number"

如果您沒有明確檢查 NaN,這可能會導致一些真正奇怪的結果。更糟的是,NaN 永遠不會等於它自己,所以你不能輕易地比較它來檢查它是否存在。

console.log(NaN === NaN); // false

TypeScript 如何提供協助

TypeScript 可以透過在編譯時強制執行適當的類型檢查和捕獲錯誤操作來緩解此問題。如果 TypeScript 可以推斷某個操作會回傳 NaN,那麼它甚至可以在程式碼運行之前拋出錯誤。

let result: number = 0 / 0; // Warning: Possible 'NaN'

TypeScript 還可以幫助您縮小 NaN 可能出現的時間和位置,從而鼓勵更好地處理數值。


4. 狂野這

JavaScript 中的 this 是最強大但最容易被誤解的概念之一。這個值完全取決於如何呼叫函數,這可能會在某些上下文中導致意外的行為。

const person = {
    name: 'Alice',
    greet() {
        console.log('Hello, ' + this.name);
    }
};

setTimeout(person.greet, 1000); // Uh-oh, what happened here?

您可能會期望在一秒鐘後看到「Hello, Alice」列印出來,但相反,您會得到 Hello, undefined。為什麼?因為setTimeout裡面的this指的是全域對象,而不是person對象。

TypeScript 如何提供協助

TypeScript 可以透過使用沒有自己的 this 的箭頭函數來幫助您避免此類問題,並保留它們所在物件的上下文。

const person = {
    name: 'Alice',
    greet: () => {
        console.log('Hello, ' + person.name); // Always refers to 'person'
    }
};

setTimeout(person.greet, 1000); // No more surprises!

這種行為不會再出乎意料了。 TypeScript 迫使您考慮上下文並幫助您正確綁定它,從而降低奇怪的未定義錯誤的風險。


5. Function Hoisting: When Order Does Not Matter

JavaScript functions are hoisted to the top of the scope; that means you can invoke them even before you have declared them in your code. This is kind of a cool trick, but can also be confusing if you are not paying attention to what's going on.

greet();

function greet() {
    console.log('Hello!');
}

While this can be convenient, it can also cause confusion, especially when you're trying to debug your code.

This works just fine, because of function declaration hoisting. But it can make your code harder to follow, especially for other developers (or yourself after a few months away from the project).

How TypeScript Helps

TypeScript does not change how hoisting works but it gives you clearer feedback about your code's structure. If you accidentally called a function before it is defined, TypeScript will let you know immediately.

greet(); // Error: 'greet' is used before it’s defined

function greet() {
    console.log('Hello!');
}

TypeScript forces you to do some cleanup, where your functions are declared before they are used. It makes your code much more maintainable this way.


Wrapping It Up

JavaScript is an amazing language, but it can certainly be quirky at times. By using TypeScript, you can tame some of JavaScript’s weirdest behaviors and make your code safer, more reliable, and easier to maintain. Whether you’re working with null and undefined, taming this, or preventing NaN disasters, TypeScript gives you the tools to avoid the headaches that can arise from JavaScript’s flexible—but sometimes unpredictable—nature.

So next time you find yourself puzzling over a strange JavaScript quirk, remember: TypeScript is here to help!

Happy coding!

以上是JavaScript 的有趣之處以及 TypeScript 如何讓它變得更好的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn