Hello
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # Deep JS Foundations, v3 ###### tags: `javascript` Original from Kyle Simpson's course [Deep JavaScript Foundations, v3](https://frontendmasters.com/courses/deep-javascript-v3/) in [Frontend Master](https://frontendmasters.com/) 原出處為[前端大師](https://frontendmasters.com/) - Kyle Simpson[深入JavaScript基礎 V3](https://frontendmasters.com/courses/deep-javascript-v3/) ## Index 索引 - [Introduction 簡介](#Introduction) - [Types 類型](#Types) - Primitive Types (基本類型) - Abstract Operations (抽象操作) - Coercion (強制轉型) - Equality (相等比較) - TypeScript, Flow, etc. - [Scope 範疇/範圍](#Scope) - Nested Scope (巢狀範疇) - Hoisting (提升) - Closure (閉包) - Modules (模組) - [Objects (Oriendted) 物件(導向)](#Objects) - this - class {} - Prototypes - OO vs. OLOO ## Introduction 簡介 Why we need to learn JavaScript deeply, before jump in to the framework or library. 在進入框架及函式庫之前,為什麼我們需要深入學習JavaScript呢? When bugs happen, and most of developer blame, includes language, framework, library, but I think most of them just want to shirk responsibility. 許多開發者在面對bug時會將責任推給語言、框架或是函式庫,但就我而言這是在推卸責任。 > Whenever there's a divergence between what your brain thinks is happening, > and what the computer does, > that's where bugs enter the code. 事實上bug更像是你的想法與電腦運算方式的分歧。 Try yourself to explain the following example: 請試著解讀以下的範例: ```javascript= var x = 40; x++; // 40 x; // 41 ++x; // 42 x; // 42 ``` if you really understand what happend above, try next example: 若你真的了解上述的範例,試著解讀下一段: ```javascript= var x = "5"; x = x + 1; // "51" var y = "5"; y++; // ?? y; // ?? ``` If second example confuse you, you will gain a lot from this article. 第二個範例讓你感到疑惑嗎? 那麼這篇文章將對你帶來一些幫助。 ## Types 類型 ### ES Spec 2021 官方規範 - [data-types-and-values](https://tc39.es/ecma262/#sec-ecmascript-data-types-and-values) ### Primitive Types 基本類型 ECMA 2021 only defined 8 types in the spec: ECMA於2021年所公佈的規範中定義了8種類型: - undefined - null - boolean - string - symbol - number - bigint - object One of the ***misunderstanding*** of JavaScript is, ***"In JavaScript, everything is an object"***, the answer is ***false***, because ***false*** is not an object. 數個對於JavaScript的誤解之一是 --- ***在JavaScrip中,所有的東西都是物件。*** --- 這是***錯誤***的! The reason behind why people say everything is an object, is because most of the values in JavaScript can behave as objects. 的確,在JavaScript中,大部分的 value 行為可以表現得像是 object。 But we can figure out most of them are not object. 但他們並不都是物件型態,實際的分類如下表所示: | Not Object非物件 | Object物件 | | -------- | -------- | | undefined | object | | string | function | | number | array | | boolean | | | symbol | | | bigint | | | null | | > Unlike languages like C++ or Java, > ***In JavaScript, variables dont have types, values do.*** 與C++、Java不同,***在JavaScript裡,variables(變數)沒有型態,而value(值)則有型態。*** ### typeof Operator ```javascript= var v; typeof v; // "undefined" v = "1"; typeof v; // "string" v = 2; typeof v; // "number" v = true; typeof v; // "boolean" v = {}; typeof v; // "object" v = Symbol(); typeof v; // "symbol" typeof doesntExist; // "undefined" var v = null; typeof v; // "object" v = function(){}; typeof v; // "function" v = [1, 2, 3]; typeof v; // "object" var v = 42n; typeof v; // "bigint" ``` It is critical to know, ***`typeof` operator return values are `string`***. And those strings values are predictable. 很重要!很重要!很重要! ***`typeof` 運算子所回傳的值為`string`*** 而且回傳的String(字串)是可被預測的。 ### undefined vs undeclared vs uninitialized > ### undeclared > Its never been created in any scope that we have access to. > 從來沒被宣告過。 > > ### undefined > there's a variable, but at that moment, it has no value. > 已經宣告了這個變數,但是在被使用的當下沒有值。 > > ### uninitialized (aka TDZ) > the certain variable, dont get initialized. > 尚未被初始化(指定值)的變數。又稱為TDZ。 ### Special Values 特殊值 #### NaN ```javascript= var v = Number("n/a") // NaN typeof v; // "number" ``` > typeof `NaN` returns `"number"`, > better to think about `NaN` is *invalid number* > `NaN` 回傳 `"number"`,可以想像它是個無效的數字。 --- ```javascript= var myAge = Number("0o46"); // 38 var myNextAge = Number("39"); // 39 var myCatsAge = Number("n/a"); // NaN myAge - "my son's age"; // NaN, see below ``` > When you give numerical operator something that is not a number, JavaScript Engine will turns that into number first, related to coercion. 當你把非數字丟給算術運算子,JavaScrip會強制將其轉成數值。 --- ```javascript= myCatsAge === myCatsAge; // false ``` > NaN is the only value it is not equal to itself. NaN並不會等於自己。 --- ```javascript= isNaN(myAge); // false isNaN(myCatsAge); // true isNaN("my son's age"); // true ``` > `isNaN` is early utility to check `NaN`, > but it coerces values to numbers before it checks for them. > `isNaN` 可檢查該值是否為`NaN`,但它會將值強制轉型為數值後再檢查。 --- ```javascript= Number.isNaN(myCatsAge); // true Number.isNaN("my son's age"); // false ``` > In ES6, we have `Number.isNaN` utility to check `NaN`, > this will match `NaN` exactly. > 在ES6中可以使用`Number.isNaN`的寫法來檢查`NaN`。 --- ```javascript= Object.is(NaN, NaN) // true ``` > or using `Object.is`. > 也可以使用`Object.is`來檢查`NaN`。 --- #### Negative Zero ```javascript= var trendRate = -0; trendRate === -0; // true trendRate.toString(); // "0" trandRate === 0; // true trandRate < 0; // false trandRate > 0; // false Object.is(trandRate, -0); // true Object.is(trandRate, 0); // false ``` ```javascript= Math.sign(-3); // -1 Math.sign(3); // 1 Math.sign(-0); // -0 Math.sign(0); // 0 // "fix" Math.sign(..) function sign(v) { if (v !== 0) { return Math.sign(v) } return Object.is(v, -0) ? -1 : 1; } sign(-3); // -1 sign(3); // 1 sign(-0); // -1 sign(0); // 1 ``` ### Coercion 強制轉型(型別轉換) In JavaScript, we refer to `type conversion` as `coercion`. And the first thing you need to know is that the `coercion` is an Abstract Operations. 在JavaScript裡面,我們稱`coercion`為強制轉型(型別轉換)。 首先我們要知道`coercion`是一種抽象操作。 #### ES Spec 2021 官方規範 - [Abstract Operations in tc39](https://tc39.es/ecma262/#sec-abstract-operations) #### Abstract Operations 抽象操作 The abstract operations are not a part of the ECMAScript (aka. JavaScript), they are defined to aid the specification of the semantics of language. Not need to be an actual function inside JavaScript Engine, they are conceptual operation. 抽象操作的定義是為了協助語言語義的規範,其本身並不屬於JavaScript,只是概念上的操作。 The first abstract operation that we need to know is called `ToPrimitive(input [, preferredType])`. 第一個必須知道的抽象操作為`ToPrimitive(值 [, 期望型別])`。 the `ToPrimitive` takes an optional type hint, and hint is either `string` or `number`, so if you have something that is not a primitive, this function ask you about what kind of type you would like it to be. `ToPrimitive`運算的主要用途為改變值得原始型別。 其接受一個值及一個期望型別(字串或數字),把該值轉化為我們期望的型別。 > NOTE When ToPrimitive is called with no hint, then it generally behaves as if the hint were number. However, objects may over-ride this behaviour by defining a @@toPrimitive method, like Date and Symbol. 當未告知`ToPrimitive`期望型別時,其預設會優先將值轉為數字(Number)。 但是有例外!在遇到Date(日期)及Symbol(物件)時會優先轉為字串(String)。 If we have something non-primitive, like an object, an array, a function. and we need to make it into a primitive, this is the abstract operation that's going to be involved in doing that. 當我們有非原始型別的物件、矩陣或函示必須要賦予原始型別的概念時,就會使用到`ToPrimitive`這個抽象操作。 ## Scope TODO ## Objects (Oriented) TODO

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully