shawnliu
    • 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
    • Engagement control
    • 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 Versions and GitHub Sync Note Insights Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control 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
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    # JS 語言基礎 04 -基本函式(Function)概念 ###### tags: `JavaScript` [TOC] ## 何謂函式 **"函式"指的是將一或多段程式指令包裝起來,可以重複使用,也方便維護。**(參至 0陷阱!0誤解!8天重新認識javascript) 也就是指如果在程式內,==多次使用到某程式碼時==,可以==統一整理==,定義function,以方便之後如有更動,方便統一修改,不必個別修改。 EX: ```javascript= for (var i = 1; i<10; i++){ console.log("第"+ i +"隻綿羊"); /*假若原本程式碼我們多次使用到此行, 那麼我們可以使用function方便我們做整理撰寫*/ } ``` 定義function,修改後為: ```javascript= function echoSheep(index){ console.log("第" + index + "隻綿羊");/*定義之後, * 如有修改內容,從此function下手就可以!*/ } for(var i = 1; i < 10; i++){ echoSheep(i)//以function定義,方便做統一修改 } ``` ## 定義函式的方式 ### 函式宣告(Function Declaration) 屬於最常見的用法: ```javascript= function 名稱 ([參數1,參數2,...]){ //做某事 } ``` 範例: ```javascript= function square(namber){ return number * number; } ``` ### 初步認識函式陳述式(Function Statement) 從上面宣告方式也可以進一步去看關於陳述式的部分, **陳述式**指的是: 藉由直接給定函式名稱來宣告一個函式,為一般函式宣告 ### 初步認識函式表達式(或稱表示式)(Function Expressions) 表達式(表示式)為直接把一個函式指派給另一個變數,因此除了一般的宣告外,函式也能夠作為被指派的值。 範例: ```javascript= var square = function (number) { return number * number; } ``` 而以上範例可知,function後並沒有定義++名稱++,此為==匿名函式==, ### 如何撰寫函式 上述介紹完function形式後,我們以白話點的方式幫助我們日後撰寫function,首先前面提及==函式指的是將一或多段程式指令包裝起來,可以重複使用,也方便維護。== 意思為在一段程式碼中,我們需要判別哪些變數會在之後需要改變, 由以下a物品及b物品的價格及顧客要來購買的例子來解釋: ```javascript= var aPrice = 5;//a價格 var bPrice = 4;//b價格 var Whobuytotal = aPrice + bPrice;//顧客買的總價格 console.log("ME" + MYbuytotal);//計算一個顧客買的價格 ``` 上述程式碼判斷,我們可以得知: > 1. a物品價格及b物品價格為不會改變的變數, > 2. 會改變的變因為: 顧客名、a、b物品數量, > 3. 確定完之後,我們需要計算每個顧客購買的總價格,因此設定function,讓他專門return給我們結果。[color=#ff5555] ```javascript= var aPrice = 5; var bPrice = 4; var Whobuytotal: Whobuytotal = aPrice + bPrice; //function名字(參數,參數,參數) function buy(Name,aNum,bNum){ return Name+(aPrice * aNum + bPrice * bNum) } console.log("John",3,3); console.log("BOB",4,5); ``` ### 變數的有效範圍-作用域(scope) Function是一個作用域, 舉例而言: ```javascript= var a = 100;//為下方console.log(a) function helloWorld(){ var a = 150; console.log(a)//為下方helloWorld() } helloWorld(); console.log(a); ``` 印出來的數字(a)為 150(helloWorld()的結果) 100(console.log(a)的結果) 由此結果可知function為作用域,==前提為必須在function裡加上var or let==,才不會污染其他變數。 必須注意,如果未加var,那剛才的程式運算結果將為 150 150 - function 可以影響外層已經宣告的變數,但外層無法影響function內宣告的變數,==因此,寫在函式(function)內,若無var、let、const的變數,會變成全域變數== #### P.S 全域變數與區域變數 function內為區域變數,外為全域變數,大至window,(window為根物件),而在JS內,全域變數更準確來說,應該為全域物件(或為頂層物件),以瀏覽器來說即為window,在node環境中則叫做global。 ### 提升(Hoisting) 關於提升的概念,覺得比較明瞭的說法參考至[卡斯伯-鐵人賽:JavaScript Function 與 Hoisting](https://wcc723.github.io/javascript/2017/12/16/javascript-hoisting/) 提升比較==類似於變數和函式的宣告先被放入記憶體==,以上述引用的連結文章來說明,以白話說明,就像是++一本筆記本列了多項要做的項目,但作者翻閱筆記本並不是要開始做,而是類似備忘錄的概念,先記在腦子裡++,所以, 以文章中的舉例來說: 假如變數尚未被宣告,而使用console.log()印出,會顯示此變數未被定義。 ```javascript= 1 console.log(phone); // phone is not defined ``` 假如在var 定義變數前使用console.log(),那麼將會==顯示undefined==,表示已經==存入記憶體,但尚未有值==。 ```javascript= 1 console.log(phone); // undefined 2 var phone = 'myphone'; ``` 也就是我們可以解讀為以下的樣子: ```javascript= 1 var phone;//只有宣告語法被存入記憶體之中 2 console.log(phone); // undefined 3 var phone = 'myphone'; ``` 因此,因為這樣**變數提升**的特性,請必須將++變數都盡量在scope的最上面==先宣告==完成再使用。++ ### let、const的暫時性死區 結論: ==盡量不要再用var來宣告變數,改用let與const,而且優先使用const,除非需要再指定值才用let。== - “ const ”— 一般使用在識別值(identifier)不會被重新指定值。 - “let”— 一般使用在變數(variable)可能會被重新指定值。 引用參考資料至: [ES6篇 - let與const](https://eyesofkids.gitbooks.io/react-basic-zh-tw/content/day05_es6_let_const/) [JavaScript: var, let, const 差異](https://medium.com/@totoroLiu/javascript-var-let-const-%E5%B7%AE%E7%95%B0-e3d930521230)

    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