SD yho
    • 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
    ### ES5 已經有的defineProperty/物件get set 方法 #### 原本物件 vs defineProperty https://huanming.medium.com/%E9%87%8D%E6%96%B0%E4%BA%86%E8%A7%A3-javascript-7-object-defineproperty-c1f62d59004f 靜態方法 Object.defineProperty() 會直接對一個物件定義、或是修改現有的屬性。執行後會回傳定義完的物件。 ``` // defineProperty 預設不能寫入 let num = { a: 1, b: 2, c: 3, } // 依序帶入物件、屬性、參數 Object.defineProperty(num, 'a' { value: 4, writable: true, configurable: true, enumerable: true, }) ``` #### 針對已經有的屬性定義getter/setter ``` let wallet = { total: 100, } Object.defineProperty(waller, 'save', { configurable: true, // 新增這這兩行,原本預設是 false enumerable: true, // 新增這這兩行,原本預設是 false set: function(price) { this.total = this.total + price / 2 }, get: function() { return this.total / 2 } }) ``` #### Vue2以defineProperty建立響應式 如果一個物件已經有的屬性可以設置get/set 偵測讀or寫入,簡單來說就可以設計一些追蹤資料更新邏輯在裡面(酷~) **但有一個明顯缺點,如果使用者對原本的物件新增一個屬性,要怎們偵測跟原本物件沒有這個屬性,並且能夠新增?** https://juejin.cn/post/6985542810900365349 ``` function defineReactive (obj,property,val,customSetter,shallow) { observe(val) Object.defineProperty(obj, property, { get() { return val }, set(newVal) { val = newVal } }) } // observer 簡單來說就是遍歷物件有沒有這個屬性 walk (obj: Object) { const keys = Object.keys(obj) for (let i = 0; i < keys.length; i++) { defineReactive(obj, keys[i]) } } ``` ### 理解ES6 Proxy和Reflect defineProperty偵測層面是針對物件屬性,ES6 Proxy則是針對物件變動去設計。 ``` // 原本響應式物件 const obj = { foo: 1 // 新增一個函數 bar() { return this.foo } } const p = new Proxy(obj, get(target,key) { track(target,key) return target[key] } set(target,key,newVal) { target[key] = newVal trigger(target,key) } ) console.log(p.bar) // 1 ``` JS物件本身已有get/set屬性,不過是針對已經建立的屬性進行操作 https://pjchender.dev/javascript/js-object/#gettersetter https://playcode.io/javascript/getter-setter https://www.explainthis.io/zh-hant/swe/what-is-arrow-function https://kbpsystem777.github.io/You-Dont-Know-JS/scope&closures/ch5.html #### **isShallow 淺追蹤** https://vuejs.org/guide/extras/reactivity-in-depth.html#integration-with-external-state-systems Vue 官網其實有提到,因為reactive本身是監測物件內每一個屬性有變化就需要觸發更新流程,本身是耗費CPU計算和記憶體的。 immer和Vue shallow結合,簡單來說透過immer代理每一次變動回傳一個變動後的物件,再丟入Vue shallow賦予它新的物件進行監聽,因為Vue 只需要監聽最外層屬性,所以對於大物件能夠結省效能。 immer 實作原理 https://juejin.cn/post/6926099651510665230 ``` import produce from 'immer' import { shallowRef } from 'vue' export function useImmer(baseState) { const state = shallowRef(baseState) const update = (updater) => { state.value = produce(state.value, updater) } // state.value 就是原本Vue的響應式物件 return [state, update] } ``` **Vue Ref源碼解讀** https://juejin.cn/post/7065985754177994788 ``` class RefImpl<T> { private _value: T // 輸入新的值 private _rawValue: T // 紀錄原本的值 public dep?: Dep = undefined // 追蹤effect 的key值 public readonly __v_isRef = true constructor( value: T, public readonly __v_isShallow: boolean, ) { this._rawValue = __v_isShallow ? value : toRaw(value) this._value = __v_isShallow ? value : toReactive(value) } // isShallow 只需要第一層物件有響應式 // toRaw 將響應式物件Prxoy變成原本的物件 // toReactive 轉成響應式物件 get value() { trackRefValue(this) // 追蹤有用到它的相關變數 return this._value } // 當我們對響應式資料賦值------- set value(newVal) { const useDirectValue = this.__v_isShallow || isShallow(newVal) || isReadonly(newVal) newVal = useDirectValue ? newVal : toRaw(newVal) if (hasChanged(newVal, this._rawValue)) { this._rawValue = newVal this._value = useDirectValue ? newVal : toReactive(newVal) triggerRefValue(this, DirtyLevels.Dirty, newVal) } } } // hasChange 用的的是 Object.is (物件需要在同一索引位置) // 如果本身沒有使用shallow選項 則Vue自動轉換成toReative 深層式監聽物件 ``` #### Reactive 本身是深層監聽的 https://github.com/vuejs/core/blob/main/packages/reactivity/src/baseHandlers.ts https://juejin.cn/post/6951974032145121293 如果傳入的是物件,會對每一層屬性進行Prxoy屬性設定攔截器,這樣比如 ex: Product.name.id 更深層的數據變化才能監測到 Reactive handler 這裡也能利用isObject 攔截到非物件形式資料,避免Proxy error ``` if (isObject(res)) { // Convert returned value into a proxy as well. we do the isObject check // here to avoid invalid value warning. Also need to lazy access readonly // and reactive here to avoid circular dependency. return isReadonly ? readonly(res) : reactive(res); // 重点在这里。。。 } return res; ```

    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