<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Bun Chen on Medium]]></title>
        <description><![CDATA[Stories by Bun Chen on Medium]]></description>
        <link>https://medium.com/@bun.coding?source=rss-4a9b61d35423------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*iSqrdENANUAkinQm_8ev7A.jpeg</url>
            <title>Stories by Bun Chen on Medium</title>
            <link>https://medium.com/@bun.coding?source=rss-4a9b61d35423------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 20:42:36 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@bun.coding/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[JavaScript OOP 筆記：function → prototype → new → class]]></title>
            <link>https://medium.com/@bun.coding/javascript-oop-%E7%AD%86%E8%A8%98-function-prototype-new-class-c0dee3b4fac9?source=rss-4a9b61d35423------2</link>
            <guid isPermaLink="false">https://medium.com/p/c0dee3b4fac9</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[objectorientedprogramming]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[prototype-chain]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Bun Chen]]></dc:creator>
            <pubDate>Fri, 18 Sep 2026 09:38:05 GMT</pubDate>
            <atom:updated>2026-10-15T08:00:37.677Z</atom:updated>
            <content:encoded><![CDATA[<p>JavaScript 裡建立物件的方式有很多種，這裡整理四種方式：<strong>一般函式、原型鏈、</strong><strong>new 關鍵字、</strong><strong>class 語法糖，</strong>拆解 JavaScript 物件導向的底層機制。</p><h4>Solution 1. 用函式產物件</h4><blockquote><em>缺點❌<br>每個新創建的 </em><em>user 物件，都有邏輯一樣但 reference 不同 </em><em>increment 函式</em></blockquote><pre>function userCreator1(name, score) {<br>  const newUser = {};<br>  newUser.name = name;<br>  newUser.score = score;<br>  newUser.increment = function () {<br>    newUser.score++;<br>  };<br>  return newUser;<br>}<br><br>const user1A = userCreator1(&#39;Ari&#39;, 3);<br>const user1B = userCreator1(&#39;Jae&#39;, 5);<br>user1A.increment();<br>console.log(user1A); // { name: &#39;Ari&#39;, score: 4, increment: [Function (anonymous)] }<br>console.log(user1A.increment === user1B.increment); // false</pre><h4>Solution 2. 用原型鏈</h4><blockquote><em>💡</em><strong><em>什麼是原型鏈(prototype chain)?<br>- </em></strong><em>每個物件都有一個內建的隱藏屬性 </em><em>[[Prototype]]。<br>- </em><em>[[Prototype]] 也是物件，所以也會有一個內建的隱藏屬性 </em><em>[[Prototype]] (層層往上)。<br>- 最後一層是 </em><em>Object.prototype，這是 JavaScript 定義的根節點，它的 </em><em>[[Prototype]] 值定義是 null。<br>- 當物件找不到該屬性時，會找它的 </em><em>[[Prototype]] 屬性，沒有的話再找 </em><em>[[Prototype]] 物件裡的 </em><em>[[Prototype]] 屬性，直到碰到 null 值為止。</em></blockquote><blockquote><strong><em>這一整條「物件 → </em></strong><strong><em>[[Prototype]] → </em></strong><strong><em>[[Prototype]] → … → </em></strong><strong><em>Object.prototype → null」的路徑，就叫做原型鏈。</em></strong></blockquote><ul><li>註解1: Object.create(proto) 會返回空物件，但空物件裡的 [[Prototype]] 會指向 userFunctionStore</li><li>註解2: 為什麼 increment 函式裡的 this 知道是哪個物件?<br> → user2A.increment() 觸發時，execution context 裡的 local memory，會有 this 物件且指向 increment dot 左邊的 user2A 物件</li><li>註解3: 為什麼 user2A 會有 hasOwnProperty 屬性? 因為原型鏈: user2A → userFunctionStore → Object.prototype 裡面有 hasOwnProperty 方法。</li></ul><pre>function userCreator2(name, score) {<br>  const newUser = Object.create(userFunctionStore); // 註解1<br>  newUser.name = name;<br>  newUser.score = score;<br>  return newUser;<br>}<br><br>const userFunctionStore = {<br>  increment: function () {<br>    this.score++; // 註解2<br>  },<br>};<br><br>const user2A = userCreator2(&#39;Ari&#39;, 3);<br>const user2B = userCreator2(&#39;Jae&#39;, 5);<br>user2A.increment();<br>console.log(user2A.hasOwnProperty(&#39;score&#39;)); // true // 註解3<br>console.log(user2A); // { name: &#39;Ari&#39;, score: 4 }<br>console.log(user2A.increment === user2B.increment); // true</pre><h4>Solution 3. 用 new 關鍵字</h4><blockquote><em>💡</em><strong><em>new 做了什麼?<br>1. </em></strong><em>建立 </em><em>this 物件<br>2. 把 </em><em>this 物件裡的 </em><em>[[Prototype]] 綁定到 </em><em>UserCreator3.prototype<br>3. 執行建構函式本體<br>4. 自動返回 </em><em>this 物件</em></blockquote><ul><li>註解1: 函式有兩個型態，一個是函式型態用 () 觸發，另一個是物件型態所以可以用 dot 取得值。物件型態有內建一個 prototype 屬性，預設指向空物件。</li></ul><pre>function UserCreator3(name, score) {<br>  this.name = name;<br>  this.score = score;<br>}<br><br>// 註解1<br>console.log(UserCreator3.prototype); // {}<br><br>UserCreator3.prototype.increment = function () {<br>  this.score++;<br>};<br><br>const user3A = new UserCreator3(&#39;Ari&#39;, 3);<br>const user3B = new UserCreator3(&#39;Jae&#39;, 5);<br>user3A.increment();<br>console.log(user3A); // UserCreator3 { name: &#39;Ari&#39;, score: 4 }<br>console.log(user3A.increment === user3B.increment); // true</pre><h4>Solution 4. ‘class’ 語法糖</h4><blockquote><em>💡</em><strong><em>class 是 Solution 3 的語法糖<br></em></strong><em>底層機制兩個是一樣的，但有一些差異</em></blockquote><blockquote><em>Hoisting:<br>1. </em><em>function UserCreator3 宣告會被提升，所以在宣告呼叫不會報錯<br>2. </em><em>class UserCreator4 有 TDZ，宣告前呼叫會丟 </em><em>ReferenceError 錯誤</em></blockquote><blockquote><em>Enumerable(可列舉性)，可用 </em><em>for...in、</em><em>Object.keys(prototype) 列出來<br>1. </em><em>UserCreator3.prototype.increment = function(){} 可以 enumerable<br>2. </em><em>class 裡寫的方法不能 enumerable</em></blockquote><ul><li>註解1: 寫在 class 裡的方法，會自動加到 UserCreator4.prototype 上</li></ul><pre>class UserCreator4 {<br>  constructor(name, score) {<br>    this.name = name;<br>    this.score = score;<br>  }<br><br> // 註解1<br>  increment() {<br>    this.score++;<br>  }<br>}<br><br>const user4A = new UserCreator4(&#39;Ari&#39;, 3);<br>const user4B = new UserCreator4(&#39;Jae&#39;, 5);<br>user4A.increment();<br>console.log(user4A); // UserCreator4 { name: &#39;Ari&#39;, score: 4 }<br>console.log(user4A.increment === user4B.increment); // true</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c0dee3b4fac9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AJAX 筆記：XMLHttpRequest、fetch、axios]]></title>
            <link>https://medium.com/@bun.coding/ajax-%E7%AD%86%E8%A8%98-xmlhttprequest-fetch-axios-c03cd6dbbac5?source=rss-4a9b61d35423------2</link>
            <guid isPermaLink="false">https://medium.com/p/c03cd6dbbac5</guid>
            <category><![CDATA[ajax]]></category>
            <category><![CDATA[xmlhttprequest]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[fetch-api]]></category>
            <category><![CDATA[axios]]></category>
            <dc:creator><![CDATA[Bun Chen]]></dc:creator>
            <pubDate>Thu, 10 Sep 2026 02:18:05 GMT</pubDate>
            <atom:updated>2026-09-30T02:31:57.947Z</atom:updated>
            <content:encoded><![CDATA[<h4>AJAX (Asynchronous JavaScript and XML) 技術的背景</h4><ul><li>1995 年: JavaScript 誕生，當時只有用在簡單的頁面互動 (像表單驗證)，無法在背景跟伺服器交換資料</li><li>1999 年: 微軟為了讓 Outlook Web Access 能在不刷新頁面下同步郵件，在 IE5 引入 XMLHTTP (當時伺服器回傳的資料格式大多是 XML)</li><li>2000 年: Mozilla 將這個概念實作成 XMLHttpRequest 物件，其他瀏覽器陸續跟進支援</li><li>2004 年: Google 用這技術做出了 Gmail，因為體驗很驚豔，開始帶起風潮</li><li>2005 年: Jesse James Garrett 將這種「用 JS 在背景和伺服器交換資料、更新頁面」的技術，命名為 AJAX</li></ul><p>演進到 2026 年，除了瀏覽器內建的 XMLHttpRequest 和 fetch API，工作上也常使用第三方套件 axios 來跟伺服器發送請求。</p><p>因為理解非同步對網頁開發很重要，所以我用 GET 和 POST 請求方式，分別寫出 XMLHttpRequest 、fetch、axios 的請求語法。</p><h4>共同設定</h4><ul><li>用 fake api，一天只能發送 40 次，超過的話要用 email 申請，並在 request header 放上 x-api-key</li><li>GET <a href="https://reqres.in/api/users">https://reqres.in/api/users</a></li><li>POST <a href="https://reqres.in/api/register%EF%BC%8C%E8%AB%8B%E6%B1%82%E5%8F%83%E6%95%B8%E5%A6%82%E4%B8%8B:">https://reqres.in/api/register</a></li></ul><pre>{<br>  email: &#39;eve.holt@reqres.in&#39;,<br>  password: &#39;pistal&#39;, // 可以註解掉這拿到 400 http status<br>}</pre><blockquote><em>程式碼可以參考我的 </em><a href="https://github.com/thisIsBun/xhr-fetch-axios"><em>GitHub repo</em></a></blockquote><h4>XMLHttpRequest</h4><ol><li>因為 XMLHttpRequest 是用 callback 通知結果，需要自己返回 Promise 物件才能搭配 .then()、.catch()</li><li>建立 XMLHttpRequest 實例</li><li>.open() 設定請求的方法與網址</li><li>設定 xhr.responseType = &#39;json&#39; 把 response body 轉成 JSON</li><li>.setRequestHeader() 設定 request header，像是設定 Content-Type</li><li>onload 設定拿到回應後要做的事情 → 會發現 response status 在 4XX (用戶端錯誤) 或 5XX (伺服器端錯誤) 也是會進 onload，因為 4XX 或 5XX 也算是「請求成功，伺服器有回應」，只是回應的內容是錯誤訊息</li><li>onerror 只有「網路層級」的失敗，像是網路斷線、DNS 解析失敗、CORS 被擋下等</li><li>.send() 真正的送出請求，且需要把 request body 轉成字串</li></ol><h4>fetch</h4><ol><li>fetch 本身是回傳 Promise 物件，而且 resolve 後拿到的是 Response 物件，所以要再呼叫 .json() 才能拿到解析好的資料</li><li>method 設定請求的方法</li><li>跟 XMLHttpRequest 一樣設定 Content-Type</li><li>跟 XMLHttpRequest 一樣要把 request body 轉成字串</li><li>跟 XMLHttpRequest 一樣，4XX 或 5XX 也是在 .then() 裡拿到</li></ol><h4>axios</h4><ol><li>可以用 .create() 設定共用 header</li></ol><p>axios 會根據 request body 格式自動設定 Content-Type、把 request body 轉成字串、連 4XX 或 5XX 都會判為 reject</p><h4>Comparison</h4><p>程式碼可以看出 XMLHttpRequest 是比較命令式 (imperative) 的寫法，要一步一步下指令 (先建立物件、設定屬性、呼叫方法)；fetch 和 axios 是比較宣告式 (declarative)，所有設定一次打包傳入。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/859/1*4alMH-IPXPtqx28lt_0qmw.png" /><figcaption>XMLHttpRequest, fetch, axios comparison</figcaption></figure><h4>結論</h4><p>從 1999 年開始有 AJAX 技術到現在，核心的概念都是「在不刷新頁面下，跟伺服器交換資料」，真正改變的只是開發者要處理多少細節。</p><p>我自己比較有感的是，工作上使用 axios 太習慣了，原來從 XMLHttpRequest 開始就不會把 4XX 或 5XX 判為錯誤。這也提醒我，即使平常有使用套件，還是要花時間了解原生的運作方式。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c03cd6dbbac5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript Type Coercion 筆記：ToNumber、ToString、ToBoolean、ToPrimitive]]></title>
            <link>https://medium.com/@bun.coding/type-coercion-%E7%AD%86%E8%A8%98-tonumber-tostring-toboolean-toprimitive-9ed7933c9208?source=rss-4a9b61d35423------2</link>
            <guid isPermaLink="false">https://medium.com/p/9ed7933c9208</guid>
            <category><![CDATA[type-coercion]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[weakly-typed]]></category>
            <dc:creator><![CDATA[Bun Chen]]></dc:creator>
            <pubDate>Sun, 30 Aug 2026 08:51:13 GMT</pubDate>
            <atom:updated>2026-09-30T08:10:19.105Z</atom:updated>
            <content:encoded><![CDATA[<p>寫 JavaScript 應該會遇到過下面的坑:</p><pre>console.log(10 + &#39;28&#39;); // &#39;1028&#39;</pre><p>這其實不是 bug，這跟 JavaScript 是弱型別有關，但什麼是弱型別? 為什麼 JavaScript是弱型別？</p><h4>弱型別(Weakly typed)</h4><ul><li>運算子(operator)在兩側(operand)資料型別不一致時，不會直接跳 TypeError</li><li>跟弱型別對比的是強型別，像是 TypeScript</li></ul><h4>為什麼 JavaScript 設計是弱型別</h4><ul><li>JavaScript 開發者 Eich 當初開發目的，是設計一個可以在瀏覽器執行的腳本語言，讓使用者可以在網頁上做互動，所以網頁不該因為型別問題掛掉。</li><li>這個設計哲學延伸出來的其中一個好處是：從 DOM 拿到的值即使都是 string(例如表單輸入)，也能直接跟數字運算，不必每次手動轉型。</li></ul><p>分享 JavaScript 開發者 Eich 在 2018 專訪時的<a href="https://www.infoworld.com/article/2256143/interview-brendan-eich-on-javascripts-blessing-and-curse.html">影片</a>，他後悔 ==寬鬆比較的設計，因為這違反了相等的邏輯。(影片 7:20 開始)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9UlexJg1AEIrXPAOgN5Saw.png" /><figcaption>2018 年 Brendan Eich 的訪談</figcaption></figure><pre>console.log(&#39;&#39; == 0);   // str vs num -&gt; str coerced to num -&gt; 0 == 0 -&gt; true<br>console.log(0 == &#39;0&#39;);  // num vs str -&gt; str coerced to num -&gt; 0 == 0 -&gt; true<br>console.log(&#39;&#39; == &#39;0&#39;); // str vs str -&gt; no coercion -&gt; &#39;&#39; !== &#39;0&#39; -&gt; false<br><br>// 如果 &#39;&#39; == 0 且 0 == &#39;0&#39; 都成立<br>// 照數學上「相等」該有的傳遞性，&#39;&#39; == &#39;0&#39; 應該也要是 true，但實際上是 false<br>// 這就是 Eich 說的「違反了重要的數學性質」。</pre><p>看上面例子，其實 JavaScript 的 type coercion 是有規則的。JavaScript 主要有四種型別轉換:</p><h4>1. ToNumber</h4><p>coercion hint: operator(- , *, /, %, **)、unary+、Number()</p><pre>console.log(&#39;10&#39; - 7);  // 10 - 7 -&gt; 3<br>console.log(&#39;10&#39; * 7);  // 10 * 7 -&gt; 70<br>console.log(&#39;10&#39; / 2);  // 10 / 2 -&gt; 5<br>console.log(&#39;abc&#39; - 7)  // &#39;abc&#39; can&#39;t coerce to num -&gt; NaN<br>console.log(+&#39;28&#39;)      // 28</pre><h4>2. ToString</h4><p>coercion hint: operator(+ 且其中一個 operand 是字串時)、String()、${}</p><pre>console.log(10 + 28);   // 38<br>console.log(10 + &#39;28&#39;); // &#39;1028&#39;<br>console.log(true + &#39;&#39;); // boolean + str -&gt; true coerced to str -&gt; &#39;true&#39;</pre><h4>3. ToBoolean</h4><p>coercion hint: if、while、三元運算子的條件判斷、!、&amp;&amp; 和 || 的短路邏輯、Boolean()</p><pre>// 只有下面 8 個值會被轉成 false (falsy values)<br>console.log(Boolean(null));<br>console.log(Boolean(undefined));<br>console.log(Boolean(false));<br>console.log(Boolean(NaN));<br>console.log(Boolean(0));<br>console.log(Boolean(-0));<br>console.log(Boolean(0n)); // BigInt<br>console.log(Boolean(&#39;&#39;));</pre><p>在查 <a href="https://developer.mozilla.org/en-US/docs/Glossary/Falsy">MDN</a> 時，發現 document.all也是 falsy value。因為早期只有 IE 瀏覽器支援 document.all，所以很多網站都用 if (document.all) 判斷瀏覽器類型，為了讓這些老程式碼在其他瀏覽器上可以正常運作(判斷為 false)，所以放進規範裡。</p><h4>4. ToPrimitive</h4><p>會不會覺得下面程式碼很怪，time1 是 object 但卻可以像數字一樣做運算 ?!</p><p>這是因為 Date 有內建 [Symbol.toPrimitive]，會根據不同的觸發，把物件轉成原始值(primitive)</p><pre>const time1 = new Date();<br>const time2 = new Date();<br><br>console.log(typeof time1);   // object<br>console.log(time1 - time2);  // 0</pre><p>不只有 Date，一般的物件也可以自己設定 [Symbol.toPrimitive] ，還可以根據不同的 coercion hint 設定不同的輸出。</p><p>可能的 coercion hint 有三種:</p><ul><li>Number hint</li><li>String hint</li><li>no hint</li></ul><pre>const obj = { num: 10, str: &#39;hello&#39; };<br><br>obj[Symbol.toPrimitive] = (hint) =&gt; {<br>  if (hint === &#39;number&#39;) {<br>    return obj.num;<br>  }<br><br>  if (hint === &#39;string&#39;) {<br>    return obj.str;<br>  }<br><br>  return 20;<br>};<br><br>console.log(Number(obj)); // 10<br>console.log(String(obj)); // &#39;hello&#39;<br>console.log(obj + 28); // hint != num 且 hint != str -&gt; 20 + 28 -&gt; 48</pre><p>回頭看文章一開始的例子，console.log(10 + &#39;28&#39;) ，是因為 operator + 且 operand &#39;28&#39;，所以觸發 ToString coercion。原本以為是 bug，但其實是有跡可循的。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/1*hIiWZS4hnM3Qr-DeTJWX6g.png" /><figcaption><a href="https://262.ecma-international.org/9.0/#sec-ecmascript-language-expressions">ECMA-262</a></figcaption></figure><p>知道規則不代表要依賴它，而是更明白為什麼比較值的時候是用 === 而不是 ==，以及需要轉型別時，應該用顯性 Number()、String()、Boolean() 讓程式碼一目瞭然意圖。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9ed7933c9208" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript Closure 筆記：從 memory、execution context 切入]]></title>
            <link>https://medium.com/@bun.coding/closure-%E7%AD%86%E8%A8%98-%E5%BE%9E-memory-execution-context-%E5%88%87%E5%85%A5-83e06cefb95a?source=rss-4a9b61d35423------2</link>
            <guid isPermaLink="false">https://medium.com/p/83e06cefb95a</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[execution-context]]></category>
            <category><![CDATA[memory-management]]></category>
            <category><![CDATA[closure]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Bun Chen]]></dc:creator>
            <pubDate>Wed, 26 Aug 2026 01:25:51 GMT</pubDate>
            <atom:updated>2026-09-30T01:54:45.098Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><strong><em>TL;DR:</em></strong><em> 先從 memory、call stack、execution context 講起，到 Closure 為什麼能讓 inner function 記住已經消失的 outer function 變數，並用 DevTools debugger 看 closure。</em></blockquote><p>在看 closure 之前，我覺得要先了解程式碼執行時，JS engine 裡的 memory、call stack 和 execution context 在做什麼</p><h4><strong>memory</strong></h4><ul><li>用來記憶宣告的值和指派的值</li><li>會依程式碼上到下順序記憶</li><li>像全域變數和區域變數一樣，有分 global memory 和 local memory</li><li>local memory 是指在 {} 裡的變數，像是函式觸發時如果有帶 argument，那 local memory 第一個紀錄的就是 argument</li></ul><h4><strong>call stack</strong></h4><ul><li>用來記錄目前觸發的函式，是先進後出的堆疊方式，執行結束的就會 pop out，然後執行下一個 → FILO (first in, last out) 先進後出的資料結構</li><li>call stack 最底層通常是 global execution context，所有函式呼叫都是疊在它上面</li></ul><h4><strong>execution context</strong></h4><ul><li>每當函式被呼叫時，就會建立一個新的 execution context</li><li>執行完畢的 execution context 會從 call stack pop 出去，對應的 local memory 才會跟著被清除</li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FzdGfo6I1yrA%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DzdGfo6I1yrA&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FzdGfo6I1yrA%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/e5e9d5478005482dac360699ea72b337/href">https://medium.com/media/e5e9d5478005482dac360699ea72b337/href</a></iframe><p>execution context 在執行完畢後會移除，所以應該就讀取不到這 execution context 裡的 local memory 變數。</p><p>但很神奇的，當一個函式(outer function)裡面有宣告另一個函式(inner function)時，outer function 執行完畢 execution context 已經移除了，還是可以透過 inner function 來操作定義在 outer function 裡的變數，這就是 Closure(閉包)。</p><h4>Closure 的發生就是在 outer function 的 execution context:</h4><ul><li>local memory 除了 outer function 的變數，還會有另一個 inner function</li><li>最後把 inner function return 出去 (不限於 return，只要 inner function 能以任何方式脫離 outer function 的生命週期)</li></ul><p>這時的 inner function 不是只有函式，還會帶上(backpack)只有定義在 outer function 的變數，所以 outer function 就算已經執行結束了，inner function 還是可以取得 outer function 變數，這就是 closure。</p><h4>QA</h4><p><strong>1. Closure 的特性，是否會讓 inner function 記憶一些沒有使用但定義在 outer function 的變數?</strong></p><blockquote><em>JS engine(像是 Chrome V8) 通常會做優化，只保留 inner function 實際有使用到的變數，這樣可以減少記憶體佔用。</em></blockquote><p><strong>2. 不同的 outer function 呼叫取得的 inner function，彼此之前是各自操作 outer function 變數嗎?</strong></p><blockquote><em>對，因為每次呼叫 outer function 都會建立全新的 execution context 和 local memory，inner function 是在 outer function 呼叫時才被建立，並透過 lexical scope 指向那次呼叫的 local memory，所以彼此互不干擾。</em></blockquote><h4>用 DevTools 看 inner function 的 closure</h4><ol><li>在程式碼放 debugger 就可以從 devtools 看到程式碼逐步的執行過程</li></ol><pre>debugger<br><br>function outer() {<br>  let counter = 0;<br><br>  function inner() {<br>    counter++;<br>    console.log(counter);<br>  }<br><br>  return inner;<br>}<br><br>const newFunc = outer();<br><br>newFunc();<br>newFunc();</pre><p>2. 先停在 line 15，要開始呼叫 inner function</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/1*hYsQx2QfquPlDEg2qth8VQ.png" /></figure><p>3. 進到 inner function 後，會看到 Closure (outer) 資料</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/1*EGaGaiu_X7y3inB4cPiHgg.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=83e06cefb95a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[2025 year in review]]></title>
            <link>https://medium.com/@bun.coding/2025-year-in-review-aa65c2255f8e?source=rss-4a9b61d35423------2</link>
            <guid isPermaLink="false">https://medium.com/p/aa65c2255f8e</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Bun Chen]]></dc:creator>
            <pubDate>Tue, 17 Feb 2026 06:45:53 GMT</pubDate>
            <atom:updated>2026-02-18T12:08:38.451Z</atom:updated>
            <content:encoded><![CDATA[<p>2025 年在每個面向都累積了一點技術與經驗。</p><p>回顧這一年，我覺得自己最大的收穫，是從「把需求完成」逐漸成長為「能獨立設計架構」的前端工程師。</p><h4>工作成長｜獨立完成大型功能</h4><p>在過去的開發經驗中，我主要負責的是較小型的功能開發，例如在既有功能上新增指定需求。雖然有累積實作經驗，但對整體系統架構的理解比較偏片段。</p><p>2025 年開始，我逐漸有機會參與較大型的功能模組，從架構設計、元件拆分到狀態管理。這讓我開始培養維護系統的能力，不只是單點的功能實作。</p><p>我覺得自己提升最有感的是在狀態管理和資料流設計，我開始會刻意避免：不必要的 API 呼叫、避免資料在多個地方更動導致 debug 的困難等。</p><p>另外開發節奏的掌握，也是我有感提升的。在設計好開發架構與開發順序後，我發現我要優先處理核心或實作困難的元件，避免高風險元件留到最後開發會降低開發品質。</p><h4>技術增進｜後端與資料庫</h4><p>後端對我來說曾經像是個黑盒子。我對後端怎麼處理邏輯和資料庫等概念是模糊的。我甚至曾經很疑惑，為什麼後端的 console.log 是從終端機看到，哈哈！</p><p>2025 年因為 AC 的學習平台即將關閉，我趁機好好把後端課程上完，包含：HTTP request flow、MVC 分工、串接資料庫等。</p><p>我覺得這對我理解公司專案架構很有幫助，像是我開始會透過 docker log 查看後端服務訊息、會觀察本機資料庫的資料、必要時也會執行 SQL 調整本機資料。</p><h4>基礎打底｜資料結構與演算法</h4><p>我在 2023 年時開始接觸 LeetCode，起因是 AC 的朋友發起的每週一題的活動。這讓我意識到，自己對於「如何有效率處理資料」的概念很模糊。</p><p>所以 2025 年初，我在 Udemy 上選了 JavaScript 資料結構與演算法的課程，才逐漸建立起對時間複雜度、空間複雜度的概念。</p><p>2025 年其中一個目標是「每週解一題 LeetCode」，這目標也讓刷題成為固定的學習節奏。</p><p>這樣的學習讓我在寫邏輯時，會更有意識地思考「如何降低迴圈次數」，也提升了我對 JavaScript 的掌握，讓我更熟悉各種 built-in methods 的使用時機。</p><h4>總結 2025</h4><p>對我來說，2025 是穩定累積的一年。</p><p>讓我逐漸建立起系統設計的視角，思考整體架構與維護。有後端和資料結構的學習，也讓我的技術能力更加完整。</p><p>已經開始的 2026 年，對我來說也會是充滿挑戰的一年，因為要負責公司第一個客製產品。期待自己在新的挑戰中，能持續累積技能。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aa65c2255f8e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[2024 year in review]]></title>
            <link>https://medium.com/@bun.coding/2024-year-in-review-ffa72c6ffbc6?source=rss-4a9b61d35423------2</link>
            <guid isPermaLink="false">https://medium.com/p/ffa72c6ffbc6</guid>
            <category><![CDATA[2024]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[developer]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[frontend]]></category>
            <dc:creator><![CDATA[Bun Chen]]></dc:creator>
            <pubDate>Tue, 07 Jan 2025 07:46:16 GMT</pubDate>
            <atom:updated>2025-01-07T08:49:06.263Z</atom:updated>
            <content:encoded><![CDATA[<p>2024 年是我成為軟體工程師的第一個完整年度，所以想來回顧一下這一年做了什麼。</p><h3>2024年設定的目標</h3><h4>增進對產品的理解</h4><p>為什麼?</p><p>公司是 B2B產品，在分析需求時經常需要花時間理解功能。</p><p>怎麼做?</p><ul><li>每個 sprint的需求開發前，先從使用者角度出發，思考使用者是遇到什麼問題、會怎麼操作等。</li><li>遇到比較難理解的需求時，我會整理出我不理解的地方跟 PM討論，藉此得到更全面的需求背景，甚至 PM會提到更多前因後果。</li></ul><p>成果?</p><ul><li>開發過程中，因為有更清晰的評估需求是否滿足使用者，覺得有增加實作效率。</li><li>透過這樣來回的討論，有更認識團隊成員，增加團隊的協作。</li></ul><h4>增加程式理解力</h4><p>為什麼?</p><p>這是軟體工程師必備，這會影響到產品的進展跟穩定度。</p><p>怎麼做?</p><ul><li>覺得很幸運身邊的老闆是那種能力很強的人，我發現他除了軟體能力很好以外，遇到問題時他很穩定，然後逐步把問題範圍縮小。</li><li>我是利用技術文件梳理脈絡，最近在重新看 React Dev官網，發現在寫了一年多 React後重新有更深層的理解。</li></ul><p>成果?</p><ul><li>印象某次非同步邏輯開發，code review時來回跟老闆討論。在那次討論後我覺得對非同步的理解有增加了，因為我提出可以成功說服他的方式。</li><li>某次 QA回報的 bug在我跟我老闆的本機環境都複製不到，後來我遠端後發現是預設值不同導致，所以成功解決，這讓我增加 debug的信心。</li></ul><h4>實作 side project</h4><p>為什麼?</p><p>覺得寫 side project是驗收現有技能和探索新技術的好機會。</p><p>成果?</p><ul><li>我今年寫了個人網站，主要是想驗收我現有技能。</li><li>也讓我初次接觸 TypeScript，雖然剛開始設定類型比較麻煩，但設定後就可以大大減少類型的錯誤。</li></ul><h3>2024年回顧和推薦</h3><h4>Web Dev Simplified — Web Developer Roadmap For 2024</h4><p>背景:</p><ul><li>這是 2024年初 WDS推出的前端學習 roadmap，內容有包含 HTML, CSS, JavaScript, React等影片，也有規劃可以實作的 projects。</li><li>連結: <a href="https://www.youtube.com/watch?v=Gc4Xh8u19NU">https://www.youtube.com/watch?v=Gc4Xh8u19NU</a></li></ul><p>心得:</p><ul><li>影片我看到 React，projects我是做到 JavaScript。</li><li>一開始學前端時，覺得 Kyle簡單明瞭的解說讓人很快速吸收。但工作以後比較關注細節，所以看完影片後會想找其他資料看。</li><li>蠻喜歡實作 projects的影片，可以觀察不同人寫程式碼的方式，但因為不是自己獨立完成的，會有不踏實的感覺。</li></ul><p>推薦否:</p><p>覺得這比較適合初學者或是開發有確實遇到問題的時候，是很好的入門課程。</p><h4>FreeCodeCamp — Bob Ziroll 的 TypeScript 課程</h4><p>背景:</p><ul><li>對 TypeScript 的類型檢查機制一直蠻好奇的，這課程是一個有連貫性的功能要完成，可以邊學邊實作。</li><li>連結: <a href="https://www.youtube.com/watch?v=SpwzRDUQ1GI&amp;t=3133s">https://www.youtube.com/watch?v=SpwzRDUQ1GI&amp;t=3133s</a></li></ul><p>心得:</p><ul><li>覺得 Bob Ziroll是很好的講者，設計課程緊湊，但 2小時非常充實。</li><li>很喜歡每個小節都會有 hands-on 自己實作。</li></ul><p>推薦否:</p><p>非常推薦初次接觸 TypeScript 的人，可以短時間內建立概念，課後會讓你想找其他專案來寫看看。</p><h4>Huli — 先別急著寫 leetcode</h4><p>背景:</p><ul><li>2023的時候有和朋友每周一起刷題，但因為缺乏演算法基礎，覺得有種不能深入的感覺。</li><li>連結: <a href="https://lidemy.teachable.com/p/alg101-leetcode">https://lidemy.teachable.com/p/alg101-leetcode</a></li></ul><p>心得:</p><ul><li>影片教怎麼循序漸進的解題思路，不僅是 leetcode，日常開發的問題拆解有很有幫助。</li><li>特別喜歡內建函式章節，覺得現在對內建函式有更深層的理解。</li><li>看完以後會想再去找更深入的演算法課程來看。</li></ul><p>推薦否:</p><p>非常推薦，就像 Huli開頭說的，要先學會走路，再去學跑步。而且這課程竟然是免費的，真的非常佛心。</p><h3>結尾</h3><p>覺得跟 2023年剛入職相比，2024年的我更清楚自己的目標與不足之處。 <br>希望 2025年能繼續累積軟體技術，可以每天開心地寫 code~</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ffa72c6ffbc6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Web Content Accessibility Guidelines 網頁內容無障礙指南]]></title>
            <link>https://medium.com/@bun.coding/web-content-accessibility-guidelines-%E7%B6%B2%E9%A0%81%E5%85%A7%E5%AE%B9%E7%84%A1%E9%9A%9C%E7%A4%99%E6%8C%87%E5%8D%97-8d075307686e?source=rss-4a9b61d35423------2</link>
            <guid isPermaLink="false">https://medium.com/p/8d075307686e</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[web-accessibility]]></category>
            <category><![CDATA[a11y]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[wcag]]></category>
            <dc:creator><![CDATA[Bun Chen]]></dc:creator>
            <pubDate>Thu, 29 Aug 2024 02:32:05 GMT</pubDate>
            <atom:updated>2024-08-30T09:23:13.945Z</atom:updated>
            <content:encoded><![CDATA[<p>最近在評估公司產品導入無障礙網頁設計的可能性，發現對無障礙的認知很狹隘，研究以後覺得有顛覆我對無障礙的想像，所以寫成部落格分享。</p><pre><a href="#70e3">為什麼網頁需要無障礙設計?</a> <br><a href="#7b51">使用者會怎麼瀏覽網頁？</a> <br><a href="#f4b6">W3C 開發指南和標準</a> <br><a href="#203e">WCAG 網頁內容無障礙指南</a> <br><a href="#f64e">怎麼讀 WCAG?</a> <br><a href="#2471">舉例 2.5.3 Label in Name</a> <br><a href="#2c6c">WCAG&#39;s google trends</a> <br><a href="#4c3e">參考</a> </pre><h3>為什麼網頁需要無障礙設計?</h3><p>我會有機會評估是因為公司客戶要求，因為美國的殘疾人法案 (ADA: Americans with Disabilities Act)，表示現在有越來越多資訊是從網路取得，所以美國聯邦在 2022年發布，網頁應該要提供每個人有獲取相同資訊，包含理解以及互動的機會，所以有列出政府網站和特定產業(像銀行、醫院等)的網頁，應該要提供無障礙設計。</p><p>除了法規規範，MDN也有提到網頁無障礙設計是有其他優點的:</p><ul><li>讓更多人有機會使用你的產品</li><li>無障礙網頁因為有提升 HTML語意，所以也會提升網頁的 SEO</li><li>增加公司的社會企業責任，提升企業 ESG形象</li></ul><h3>使用者會怎麼瀏覽網頁？</h3><p>大多使用者瀏覽網頁是用鍵盤滑鼠、觸控螢幕等。那其他人是怎麼瀏覽的呢？</p><p>大概可以區分以下四種：</p><ul><li>視覺障礙: 會使用聽覺取得網頁內容，像是使用螢幕閱讀器朗讀標題。另外應該避免資訊僅透過顏色傳達。</li><li>聽覺障礙: 如果內容是影片或音檔，會需要提供字幕或文字替代內容，以便他們能夠理解音訊信息</li><li>行動障礙: 手部做出精細的動作，對行動障礙者是困難的，所以通常會使用鍵盤或用語音輸入方式瀏覽網頁。老化也有可能導致行動障礙，像是視力變差，手會顫抖等🥲</li><li>認知障礙: 會需要更多時間理解網頁內容，所以網頁有清楚的導覽和一致性很重要</li></ul><h3>W3C 開發指南和標準</h3><p>要達成無障礙，需要各個技術協助才能達成</p><p>在 W3C(World Wide Web Consortium) 協會的 WAI(Web Accessibility Initiative)組織，有針對各種技術定義規範：</p><ul><li>WCAG = Web Content Accessibility Guidelines 網頁內容無障礙指南</li><li>ATAG = Authoring Tool Accessibility Guidelines 無障礙創作工具指南: Authoring Tool 是指創造網頁的工具(例如: 編輯器、內容管理系統 CMS等)，要確保工具本身對使用者是友善的，例如工具的每個部分都可以被螢幕閱讀器正確的朗讀</li><li>UAAG = User Agent Accessibility Guidelines 用戶代理無障礙指南: User Agent 是像瀏覽器、媒體撥放器等，例如要開發新的瀏覽器，要確保瀏覽器對所有使用者友善</li></ul><p>前端工程師就是要看 WCAG這份指南，會定義怎麼產出無障礙的網頁內容，例如用 aria-* 屬性提高可訪問性。</p><h3>WCAG 網頁內容無障礙指南</h3><p>目前最新的版本是 2023/5發布的 WCAG 2.2，但目前大部分網站是使用 WCAG 2.1當準則。</p><p>有四大原則:</p><ol><li>可感知 (Perceivable): 網頁內容須以使用者可接收的方式呈現給每個使用者</li><li>可操作 (Operable): 使用者可以跟網頁互動</li><li>可理解 (Understandable): 網頁內容和介面操作方式，需要是在可以被理解的範圍</li><li>穩健 (Robust): 網頁內容需要穩健，才可以被各種輔助技術可靠的讀取</li></ol><p>每個原則下會列出指南，這些指南會分成三種等級:</p><ul><li>A: 是最基本的無障礙網頁要求，沒有達到的話會影響可訪問性</li><li>AA: 大多數網頁都是以達到 AA 為目標，裡面的要求對大多數使用者來說都是合理的</li><li>AAA: 有最嚴格的無障礙要求，但實現的難度很高，甚至要調整產品 design guideline (像文本和背景的顏色對比度在 AAA是 7:1，AA只要 4.5:1)</li></ul><h3>怎麼讀 WCAG?</h3><p>可以從 <a href="https://www.w3.org/WAI/WCAG22/quickref/">How to Meet WCAG (Quick Reference)</a> 下手，裡面已經列出每個指南的標準了，我自己看的方式是:</p><ol><li>Understanding X.X.X: 理解這個指南的目的是解決什麼問題</li><li>Sufficient Techniques: 會說明要實現這個指南要有什麼技術，會舉例，下面也有測試方式</li><li>Failures: 會說明什麼情況會失敗，會點出大家常失敗的案例</li></ol><figure><img alt="how to read WCAG guidelines" src="https://cdn-images-1.medium.com/max/1024/1*h8_4lZMcR8mf7kjOipRlew.png" /><figcaption>how to read WCAG guidelines</figcaption></figure><h3>舉例 2.5.3 Label in Name</h3><p>這是一個 A 等級的指南，盤點一下公司專案，發現有好多地方要調整😆</p><p><strong>主要目的:</strong></p><p>網頁裡可互動元件的標籤名稱，應該要可以作為語音輸入的名稱(accessible name)，並且正確操作頁面</p><p><strong>Accessible name 定義:</strong></p><ol><li>aria-labelledby: 在可互動元件內設定 aria-labelledby屬性，再用 id 指向標籤元件，這 id 元件內的文本則會被使用作為該可互動元件的 accessible name</li><li>aria-label: 在可互動元件上設定 aria-label屬性，這個屬性的值就是該元件的 accessible name</li><li>associated elements</li></ol><ul><li>元件內的文本: 像 &lt;button&gt;, &lt;a&gt;, table cell &lt;td&gt; 這些元件內部的文本內容，可以自動作為這些元件的 accessible name</li><li>&lt;label&gt;內的文本: 當 &lt;input&gt;和 &lt;label&gt; 綁定時，&lt;label&gt;內的文本會自動作為該 &lt;input&gt;元件的 accessible name</li><li>&lt;legend&gt;元件: &lt;fieldset&gt;內的 &lt;legend&gt;元件文本，會自動作為該 &lt;fieldset&gt;的 accessible name</li><li>&lt;caption&gt;元件: 表格的 &lt;caption&gt;元件提供了表格的 accessible name</li></ul><p><strong>範例:</strong></p><ul><li>&lt;button&gt;裡是圖案<br>雖然按鈕本身 hover時會跳 tooltip顯示按鈕名稱，但由於圖案本身沒有文本內容，所以需要在按鈕本身加上 aria-label，確保語音輸入可以操作到正確的按鈕</li></ul><figure><img alt="a pattern button, show up tooltips with name of the button when hover" src="https://cdn-images-1.medium.com/max/206/1*f2M9k5HXIB0r8J1N8rjycg.png" /><figcaption>a pattern button, show up tooltips with name of the button when hover</figcaption></figure><pre>&lt;!-- origin --&gt;<br>&lt;button&gt;<br>  &lt;svg...&gt;...&lt;/svg&gt;<br>&lt;/button&gt;<br>&lt;div... role=&#39;tooltip&#39;&gt;說明&lt;/div&gt;<br><br><br>&lt;!-- adjust: 用 aria-label設定標籤名稱 --&gt;<br>&lt;button  aria-label=&quot;說明&quot;&gt;<br>  &lt;svg...&gt;...&lt;/svg&gt;<br>&lt;/button&gt;<br>&lt;div... role=&#39;tooltip&#39;&gt;說明&lt;/div&gt;</pre><ul><li>沒有 &lt;label&gt; 的搜尋框<br>即使看的到 &lt;input&gt; 裡的 placeholder屬性，但 placeholder不能作為 accessible name，所以要用 aria-label設定，或是可以放 &lt;label&gt;元件再用 CSS隱藏</li></ul><figure><img alt="search input show placeholder, but placeholder can’t be accessible name" src="https://cdn-images-1.medium.com/max/780/1*jk4DQ-MA4WZJTTG8gf_z2w.png" /><figcaption>search input show placeholder, but placeholder can’t be accessible name</figcaption></figure><pre>&lt;!-- origin --&gt;<br>&lt;div&gt;<br>  &lt;svg&gt;...&lt;/svg&gt;<br>  &lt;input type=&quot;text&quot; placeholder=&quot;Search&quot;&gt;<br>&lt;/div&gt;<br><br>&lt;!-- adjust 1: 在 input裡增加 aria-label屬性，用 aria-label設定標籤名稱 --&gt;<br>&lt;div&gt;<br>  &lt;svg&gt;...&lt;/svg&gt;<br>  &lt;input type=&quot;text&quot; placeholder=&quot;Search&quot; aria-label=&quot;Search&quot;&gt;<br>&lt;/div&gt;<br><br><br>&lt;!-- adjust 2: 新增 &lt;label&gt;，然後用 CSS隱藏 --&gt;<br>&lt;div&gt;<br> &lt;label id=&quot;combobox-label&quot; for=&quot;search-input&quot; class=&quot;visually-hidden&quot;&gt;Search&lt;/label&gt;<br>  &lt;svg&gt;...&lt;/svg&gt;<br>  &lt;input type=&quot;text&quot; placeholder=&quot;Search&quot; id=&quot;search&quot;&gt;<br>&lt;/div&gt;<br><br>&lt;style&gt;<br>  .visually-hidden {<br>    ...<br>  }<br>&lt;/style&gt;</pre><ul><li>&lt;label&gt; 內的文本，藏在很深層的元件裡面<br>語音輸入工具可能會無法正確的識別關聯性，所以在 &lt;input&gt;增加 aria-labelledby屬性，再用 id 關聯標籤用</li></ul><pre>&lt;!-- origin --&gt;<br>&lt;label for=&quot;coke&quot;&gt;<br>  &lt;input type=&quot;checkbox&quot; id=&#39;coke&#39;&gt;<br>  &lt;span&gt;<br>    &lt;p&gt;Coke&lt;/p&gt;<br>  &lt;/span&gt;<br>&lt;/label&gt;<br><br>&lt;!-- adjust: input新增 aria-labelledby屬性 --&gt;<br>&lt;label for=&quot;coke&quot;&gt;<br>  &lt;input type=&quot;checkbox&quot; id=&#39;coke&#39; aria-labelledby=&#39;label-coke&#39;&gt;<br>  &lt;span&gt;<br>    &lt;p id=&#39;label-coke&#39;&gt;Coke&lt;/p&gt;<br>  &lt;/span&gt;<br>&lt;/label&gt;</pre><h3>WCAG&#39;s google trends</h3><p>再來想分享一下，查 WCAG關鍵字在 google trends 的熱度，全球過去五年來說，從 2022年到現在熱度增加一倍以上~</p><figure><img alt="WCAG’s global popularity in google trends has more than doubled from 2022 to now" src="https://cdn-images-1.medium.com/max/1024/1*Go4BLzp_CX0qiRq1ZgHPYA.png" /><figcaption>WCAG keyword in global from <a href="https://trends.google.com.tw/trends/explore?date=today%205-y&amp;q=WCAG&amp;hl=zh-TW">google trends</a></figcaption></figure><p>我公司還在很前期的評估階段，是用 2.1 + AA 準則，準則看不懂我也會用 devtool 參考其他大公司網頁的作法。如果也有在評估的，也可以交流一下~</p><h3>參考</h3><ul><li><a href="https://www.ada.gov/resources/web-guidance/">https://www.ada.gov/resources/web-guidance/</a></li><li><a href="https://developer.mozilla.org/zh-TW/docs/Learn/Accessibility/What_is_accessibility">https://developer.mozilla.org/zh-TW/docs/Learn/Accessibility/What_is_accessibility</a></li><li><a href="https://www.w3.org/WAI/WCAG22/quickref/">https://www.w3.org/WAI/WCAG22/quickref/</a></li><li><a href="https://trends.google.com.tw/trends/explore?date=today%205-y&amp;q=WCAG&amp;hl=zh-TW">https://trends.google.com.tw/trends/explore?date=today%205-y&amp;q=WCAG&amp;hl=zh-TW</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8d075307686e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[開發常見的深拷貝(deep copy) 方法]]></title>
            <link>https://medium.com/@bun.coding/%E9%96%8B%E7%99%BC%E5%B8%B8%E8%A6%8B%E7%9A%84%E6%B7%B1%E6%8B%B7%E8%B2%9D-deep-copy-%E6%96%B9%E6%B3%95-38827a1072e1?source=rss-4a9b61d35423------2</link>
            <guid isPermaLink="false">https://medium.com/p/38827a1072e1</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[deep-copy]]></category>
            <category><![CDATA[state-management]]></category>
            <dc:creator><![CDATA[Bun Chen]]></dc:creator>
            <pubDate>Sun, 02 Jun 2024 16:50:50 GMT</pubDate>
            <atom:updated>2024-12-29T06:41:31.989Z</atom:updated>
            <content:encoded><![CDATA[<p>會對深拷貝有感是因為有一天在工作，遇到要處理一個好幾層物件+陣列交錯的資料，一開始在想難道要每一層都 spread operator處理嗎😟，後來才想到有深拷貝的處理方式。</p><h3>什麼時候會使用到深拷貝?</h3><p>當要複製很多層的巢狀結構時，就需要使用深拷貝。<br>例如，React state是物件或陣列，要先複製原本的 state值。</p><ul><li>如果只使用 … 展開運算符號進行淺拷貝，可能會在過程中無意間更改到原本 state的值</li><li>這樣就會違反 React state的 immutable (不可變)特性，因為每個 state都應該是某個時間點的歷史資料</li></ul><pre>// 例如下面物件，data的下一層 versions也是一個陣列，那 data就是一個巢狀結構<br>// 如果要改 versions值，就要使用深拷貝方式複製<br>const [data, setData] = useState({<br>  name: &quot;wifiSetting&quot;,<br>  id: 1,<br>  versions: [<br>    { name: &quot;A805&quot;, id: 1 },<br>    { name: &quot;A208&quot;, id: 2 },<br>  ],<br>});</pre><h3>開發時有哪些深拷貝方式?</h3><p>深拷貝重點是要完全複製每層的值，讓每一層值完全獨立不被影響。以下是三種常用的深拷貝方式：</p><h3>1. 用 JSON.stringify() 和 JSON.parse()</h3><p>如果每層的值都是單純值，像是 number, string, boolean, 物件, 陣列等，可以使用 JSON寫法： JSON.parse(JSON.stringify(original))</p><p>(在只有單純值的情況下，我自己是蠻喜歡這寫法的，因為不需要載入任何套件，寫起來也很直覺)</p><p>但如果值是特殊類型，則不能使用這種寫法，因為 JSON序列化過程會讓這些值失效。特殊類型包含函式、建構函式(new Date(), new Map(), new Set()等)、Symbol等。</p><pre>const original = {<br>    name: &quot;John&quot;,<br>    address: {<br>        city: &quot;New York&quot;,<br>        country: &quot;USA&quot;,<br>    },<br>    greet: function () {<br>        console.log(`Hi, I&#39;m ${this.name}`);<br>    },<br>};<br><br>const jsonClone = JSON.parse(JSON.stringify(original));<br>console.log(original.address === jsonClone.address); // false --&gt; 因為用深拷貝方式，所以是不同 reference<br>original.greet(); // Hi, I&#39;m John<br>jsonClone.greet(); // 會出現 TypeError: jsonClone.greet is not a function 錯誤</pre><h3>2. 使用 JavaScript 內建的 structuredClone()</h3><p>如果你運行的環境是 Node.js 17以上、且值是建構函式(new Date(), new Map(), new Set()等)，可以使用 structuredClone()</p><pre>const original = {<br>    name: &quot;John&quot;,<br>    address: {<br>        city: &quot;New York&quot;,<br>        country: &quot;USA&quot;,<br>    },<br>    date: new Date(),<br>};<br><br>const structureClone = structuredClone(original);<br><br>console.log(structureClone.date === original.date); // false<br>console.log(typeof structureClone.date); // object --&gt; 表示是一個新的 Date物件</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/767/1*C1NL4emLn1iX73pFauuLxw.png" /><figcaption><a href="https://developer.mozilla.org/en-US/docs/Web/API/structuredClone#browser_compatibility">https://developer.mozilla.org/en-US/docs/Web/API/structuredClone#browser_compatibility</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hd_kgDltj8-tbAvMN1Cogg.png" /><figcaption><a href="https://caniuse.com/?search=structuredClone">https://caniuse.com/?search=structuredClone</a></figcaption></figure><h3>3. 使用第三方套件 Lodash</h3><p>在開發專案中，我們經常會使用 Lodash套件，它包含了許多有用的工具函式，包括深拷貝。</p><p>如果你的檔案只有使用 cloneDeep，那建議使用 import cloneDeep from &quot;lodash/cloneDeep” 只載入 cloneDeep工具，這樣比 import { cloneDeep } from &quot;lodash”可以節省大約 20kb空間。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xBJ9oy6XNrrBdSuo-Ty0mA.png" /><figcaption>import cloneDeep from &quot;lodash/cloneDeep”</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F8ADXy7FYEQEH2dDgJttcQ.png" /><figcaption>import { cloneDeep } from &quot;lodash”</figcaption></figure><blockquote>這是使用 VS code套件 <a href="https://marketplace.visualstudio.com/items?itemName=wix.vscode-import-cost">Import Cost</a> 計算出來的，可以呈現載入檔案的大小</blockquote><h3>結論</h3><p>以上介紹三種常見的深拷貝方式，選擇哪一種方法應該根據實際的需求決定。</p><h3>參考</h3><ul><li><a href="https://developer.mozilla.org/en-US/docs/Web/API/structuredClone">https://developer.mozilla.org/en-US/docs/Web/API/structuredClone</a></li><li><a href="https://www.lodashjs.com/docs/lodash.clone">https://www.lodashjs.com/docs/lodash.clone</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=38827a1072e1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[探索 Debounce 在 JavaScript的應用]]></title>
            <link>https://medium.com/@bun.coding/debounce-%E9%98%B2%E6%AD%A2%E5%A4%9A%E6%AC%A1%E8%A7%B8%E7%99%BC%E6%A9%9F%E5%88%B6-7b65e8d84ca1?source=rss-4a9b61d35423------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b65e8d84ca1</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[debounce]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Bun Chen]]></dc:creator>
            <pubDate>Mon, 13 May 2024 15:40:13 GMT</pubDate>
            <atom:updated>2026-09-08T02:16:00.190Z</atom:updated>
            <content:encoded><![CDATA[<h3>探索 Debounce 在 JavaScript 的應用</h3><p>最近工作剛好接到一個 debounce 需求，來研究一下。</p><h3>什麼是 debounce ?</h3><p>以 input 舉例，假設會根據 input 字串做 api request</p><ul><li>如果每輸入一個字就做 api request，那打 bun 三個字母就會送出 3個 api request，這效能會蠻差的</li><li>比較好的方式是，等輸入行為停止一段時間後，用最後輸入的內容做 api request</li></ul><h3>那要怎麼知道輸入行為停止了呢 ?</h3><ul><li>我們需要在 event觸發後，到 event handler真正執行這段程式碼，加上一個機制</li><li>這個機制可以辨別，這是 event最後一次觸發 ，再去執行 event handler</li></ul><blockquote><em>- 這種可以防止 event handler 多次觸發的機制，就叫做 debounce<br>- bounce 英文是彈跳，前面加 de 就有防止意思，debounce 就是防止彈跳</em></blockquote><h3>怎麼定義 debounce ?</h3><ol><li>函式接受一個 callback 函式，和一個 delay 延遲時間</li><li>函式會 return 一個函式:</li></ol><ul><li>如果延遲時間內，timeout有值的話，就會清除前一個 setTimeout，再重新設定一個 setTimeout</li><li>延遲時間到了，就會觸發 setTimeout 裡的 callback</li><li>…args 解釋<br>1. return的函式是一個匿名函式，使用 rest parameter接受所有傳進來的參數<br>2. args本身是陣列，再用 spread operator 拆開陣列回傳給原本的 event handler</li></ul><pre>function debounce(cb, delay = 1000) {<br>  let timeout;<br>  return (...args) =&gt; {<br>    if (timeout) {<br>      clearTimeout(timeout);<br>    }<br>    timeout = setTimeout(() =&gt; {<br>      cb(...args);<br>    }, delay);<br>  };<br>}</pre><h3>怎麼呼叫 debounce ?</h3><p>第一個參數放 event handler，第二個參數放延遲時間</p><pre>const updateDebounceText = debounce((text) =&gt; {<br>  debounceText.textContent = text;<br>}, 1000);</pre><h3>用 console 看程式碼怎麼運作</h3><pre>&lt;!-- HTML --&gt;<br>&lt;input type=&quot;text&quot;&gt;<br>&lt;div&gt;<br>  &lt;b&gt;Debounce: &lt;/b&gt;<br>  &lt;span id=&quot;debounce&quot;&gt;&lt;/span&gt;<br>&lt;/div&gt;</pre><pre>// JavaScript<br>const input = document.querySelector(&quot;input&quot;);<br>const debounceText = document.getElementById(&quot;debounce&quot;);<br><br>const updateDebounceText = debounce((text) =&gt; {<br>  console.log(&quot;updateDebounceText&quot;);<br>  debounceText.textContent = text;<br>}, 1000);<br><br>input.addEventListener(&quot;input&quot;, (event) =&gt; {<br>  console.log(&quot;event trigger&quot;);<br>  updateDebounceText(event.target.value);<br>});<br><br>function debounce(cb, delay = 1000) {<br>  console.log(&quot;debounce&quot;);<br>  let timeout;<br>  return (...args) =&gt; {<br>    if (timeout) {<br>      console.log(&quot;timeout&quot;, timeout);<br>      clearTimeout(timeout);<br>    }<br>    console.log(&quot;args&quot;, args);<br>    timeout = setTimeout(() =&gt; {<br>      cb(...args);<br>    }, delay);<br>  };<br>}</pre><h4>refresh page後，在 input 輸入 “bun”，會發生什麼事情?</h4><pre>console 印出 &quot;debounce&quot;<br>console 印出 &quot;event trigger&quot;<br>console 印出 &quot;args&quot; [&quot;b&quot;]<br>console 印出 &quot;event trigger&quot;<br>console 印出 &quot;timeout&quot; 1<br>console 印出 &quot;args&quot; [&quot;bu&quot;]<br>console 印出 &quot;event trigger&quot;<br>console 印出 &quot;timeout&quot; 2<br>console 印出 &quot;args&quot; [&quot;bun&quot;]<br>console 印出 &quot;updateDebounceText&quot; -&gt; 這時候畫面的 Debounce: 才會有 bun 顯示</pre><h4>說明:</h4><ul><li>為什麼第一個是印出 &quot;debounce&quot; ?<br>1. debounce函式的執行，是在 updateDebounceText 變數指派值的時候，所以 reload後就會印出來<br>2. debounce只有做兩件事情: 定義 timeout 變數、return 函式</li><li>為什麼 debounce return 的函式，裡面沒有 timeout 變數，卻還可以印出 timeout ?<br>這是函式 closure特性，利用 scope chain 保存函式變數，所以內層函式可以取得外層函式的變數</li></ul><h3>在 React 使用 debounce要注意元件 re-render</h3><pre>// React 可以找 lodash套件使用，就不用自己寫 debounce函式了😁<br>import debounce from &#39;lodash.debounce&#39;;</pre><p>如果 event trigger 時，也會有邏輯讓元件重新渲染 (譬如 setState)，那記得要把 debounce cache 住，避免重新渲染時再產生一個 debounce 函式。</p><p>cache 函式在 react 可能會想使用 useCallback，但會有 eslint 錯誤提醒，因為這種寫法 eslint 沒辦法判斷 debounce的依賴。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/954/1*TxEOWSEhRzUCFVDx1CflaQ.png" /><figcaption>eslint react useCallback warning</figcaption></figure><pre>const updateDebounceText = useCallback(<br>  debounce((text) =&gt; {<br>    debounceText.textContent = text;<br>  }),<br>  [],<br>);</pre><p>另一個寫法是使用 useMemo cache住 debounce:</p><pre>const updateDebounceText = useMemo(() =&gt; {<br>  return debounce((text) =&gt; {<br>    debounceText.textContent = text;<br>  }, 1000);<br>}, []);</pre><h3>參考:</h3><ul><li>WDS <a href="https://www.youtube.com/watch?v=cjIswDCKgu0">https://www.youtube.com/watch?v=cjIswDCKgu0</a></li><li>DevSage <a href="https://www.youtube.com/watch?v=DwU6Q4bCAB0&amp;t=204s">https://www.youtube.com/watch?v=DwU6Q4bCAB0&amp;t=204s</a></li><li><a href="https://kyleshevlin.com/debounce-and-throttle-callbacks-with-react-hooks/">https://kyleshevlin.com/debounce-and-throttle-callbacks-with-react-hooks/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b65e8d84ca1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build your own React — 8個步驟了解 React邏輯脈絡]]></title>
            <link>https://medium.com/@bun.coding/build-your-own-react-8%E5%80%8B%E6%AD%A5%E9%A9%9F%E4%BA%86%E8%A7%A3-react%E9%82%8F%E8%BC%AF%E8%84%88%E7%B5%A1-30bca582344a?source=rss-4a9b61d35423------2</link>
            <guid isPermaLink="false">https://medium.com/p/30bca582344a</guid>
            <category><![CDATA[concurrent]]></category>
            <category><![CDATA[reconciliation]]></category>
            <category><![CDATA[fiber]]></category>
            <category><![CDATA[build-your-own-react]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Bun Chen]]></dc:creator>
            <pubDate>Thu, 29 Feb 2024 10:44:26 GMT</pubDate>
            <atom:updated>2024-12-29T06:54:05.480Z</atom:updated>
            <content:encoded><![CDATA[<h3>Build your own React — 8個步驟了解 React運作</h3><p>Rodrigo Pombo在 2019年，用 JavaScript寫出 React的運作邏輯，一共分 8個步驟寫出 React的核心功能，像是 concurrent、fiber、reconciliation等。</p><p>自己照步驟走過一回後，覺得對 React有更進一步了解了 😍</p><pre><a href="#4c76">前言</a><br><a href="#983a">Step 0: Review</a><br><a href="#0abd">Step 1: The createElement Function</a><br><a href="#e747">Step 2: The render Function</a><br><a href="#91cc">Step 3: Concurrent Mode</a><br><a href="#08eb">Step 4: Fibers</a><br><a href="#f4f4">Step 5: Render and Commit phase</a><br><a href="#d319">Step 6: Reconciliation</a><br><a href="#3a76">Step 7: Function Components</a><br><a href="#eeae">Step 8: Hooks</a><br><a href="#aa29">參考</a></pre><h3>前言</h3><ul><li>使用 react v16.8版本</li><li>作者是使用跟 React codebase一樣的變數名稱或函式名稱</li></ul><h3>Step 0: Review</h3><p>熱身題: 瞭解 React、JSX、DOM 的運作方式</p><pre>// 用 JSX語法宣告一個 element變數<br>const element = &lt;h1 title=&quot;foo&quot;&gt;Hello&lt;/h1&gt;<br><br>// 用 JS取出指定的 DOM<br>const container = document.getElementById(&quot;root&quot;)<br><br>// 將 element放進指定 DOM<br>ReactDOM.render(element, container)</pre><p>目標: 將 React 語法轉成 JavaScript</p><h4>JSX語法:</h4><ul><li>瀏覽器直接讀 JSX會報錯，所以需要像 babel工具轉譯成 JS</li><li>babel 會呼叫 createElement() (參考 React官網 <a href="https://react.dev/reference/react/createElement">createElement</a> )</li></ul><pre>// 取出 html tag、props(沒有值要帶 null)、子元件(children)當參數<br>// 子元件如果是 JSX語法，也會再呼叫 `createElement()`<br>const element = &lt;h1 title=&quot;foo&quot;&gt;Hello&lt;/h1&gt;<br>const element = React.createElement(<br> &#39;h1&#39;,<br> { title: &#39;foo&#39; },<br> &#39;Hello&#39;<br>)</pre><ul><li>createElement() 的工作同函式命名，是要創建 react element，資料格式是物件，主要有兩個屬性: type, props</li></ul><pre>// element 經過 createElement()處理後<br>{<br>  // type: 可以是 html tag 或 function(Step7 會說明 function)<br>  type: &#39;h1&#39;,<br>  // props: 是一個物件<br>  // 有 JSX全部的屬性，像要傳到 children component的資料、事件處理的函式等<br>  // 包在 React element裡的 children，通常是另一個 React element、也可以是 string<br>  props: {<br>    title: &#39;foo&#39;,<br>    children: &#39;Hello&#39;,<br>  }<br>}</pre><h4>處理 ReactDOM.render(element, container)</h4><p>是 React改變真實 DOM的方式，可以用下面 JS取代</p><pre>// 用 element.type創建 DOM，並把屬性掛上去<br>const node = document.createElement(element.type)<br>node[&#39;title&#39;] = element.props.title<br><br>// 也幫 children建立 DOM，因為 children是字串，所以用 createTextNode 建立<br>const text = document.createTextNode(&#39;&#39;)<br><br>// 同 h1 title 屬性建立方式，用 nodeValue屬性將字串放進去<br>text[&#39;nodeValue&#39;] = element.props.children<br><br>// 把字串放進 h1 tag，再把 h1 放進 container<br>node.appendChild(text)<br>container.appendChild(node)</pre><h3>Step 1: The createElement Function</h3><p>為了可以繼續使用 JSX語法，第一步要寫自己的 createElement()。</p><h4>createElement()</h4><p>參數: type、props、children</p><ul><li>type: html tag 或 function(會在 Step7 function components 說明)</li><li>props: 是物件，用 spread operator 展開</li><li>children: 因為不確定有多少子元件所以參數用 rest operator 處理，所以 children 在使用時是一個 array。當子元件也是用 JSX 語法撰寫的，babel 會再使用呼叫 createElement()。</li></ul><p>回傳值: 會有 type和 props屬性</p><pre>function createElement(type, props, ...children) {<br>  return {<br>    type,<br>    props: {<br>      ...props,<br>      children,<br>    },<br>  };<br>}</pre><h4>範例:</h4><pre>// JSX:<br>const element = (<br> &lt;ul id=&quot;drink&quot;&gt;<br>   &lt;li&gt;Coffee&lt;/li&gt;<br>   &lt;li&gt;Tea&lt;/li&gt;<br> &lt;/ul&gt;<br>)<br><br>// babel: 呼叫 createElement():<br>const element = React.createElement(<br>  &#39;ul&#39;,<br>  { id: &#39;drink&#39; },<br>  React.createElement(&#39;li&#39;, null, &#39;Coffee&#39;),<br>  React.createElement(&#39;li&#39;, null, &#39;Tea&#39;),<br>);<br><br><br>// element 經過 createElement()處理後<br>{<br>  type: &#39;ul&#39;,<br>  props: {<br>    id: &#39;drink&#39;,<br>    children: [<br>      { type: &#39;li&#39;, props: { children: &#39;Coffee&#39; } },<br>      { type: &#39;li&#39;, props: { children: &#39;Tea&#39; } }<br>    ]<br>  }<br>}</pre><p>另外我們需要再處理，當子元件是 text node的時候:</p><ul><li>text node是指，當遇到像 &lt;h1&gt;Hello&lt;/h1&gt;語法時，Hello是一個 string</li><li>children是用 rest parameter傳進函式的 array，array item如果是 React element就會是一個 object，所以可以用這判斷。</li></ul><pre>function createElement(type, props, ...children) {<br>  return {<br>    type,<br>    props: {<br>      ...props,<br>      children: children.map((child) =&gt; (typeof child === &#39;object&#39; ? child : createTextElement(child))),<br>    },<br>  };<br>}<br><br>function createTextElement(text) {<br>  return {<br>    type: &#39;TEXT_ELEMENT&#39;,<br>    props: {<br>      nodeValue: text,<br>      children: [],<br>    },<br>  };<br>}</pre><blockquote><em>text node在 React是會自動轉換的，但這裡為了讓基本原理更好理解，所以我們自己處理這塊。</em></blockquote><h4>讓 babel使用自定義的 createElement()</h4><p>第一步: 將自定義的 React取名叫做 Didact，再使用特殊註解 /** @jsx */ ，告訴 babel怎麼處理 JSX (參考 babel官網 <a href="https://babeljs.io/docs/babel-plugin-transform-react-jsx#customizing-the-classic-runtime-import">Customizing the Classic Runtime Import</a>)</p><pre>const Didact = {<br>  createElement,<br>}<br><br>/** @jsx Didact.createElement */<br>const element = (<br>  &lt;div class=&quot;intro&quot;&gt;<br>    &lt;h1&gt;Welcome to my website!&lt;/h1&gt;<br>    &lt;p class=&quot;summary&quot;&gt;You can find my thoughts here.&lt;/p&gt;<br>  &lt;/div&gt;<br>)</pre><p>第二步: 本機專案安裝 babel</p><ul><li>因為我們重點是了解 React程式碼邏輯，所以直接安裝 React使用內建好的 babel和 config</li><li>用 <a href="https://codesandbox.io/s/didact-2-k6rbj?file=/src/index.js:542-587">Pombo codesandbox</a>裡的版本安裝</li></ul><ol><li>安裝套件: npm install — save-dev react@16.8.6 react-dom@16.8.6 react-scripts@3.0.1</li><li>仿造 React檔案放置邏輯: index.html 放到 public資料夾、index.js 放到 src資料夾</li><li>package.json增加 dev scripts</li></ol><pre>&quot;scripts&quot;: {<br>  &quot;dev&quot;: &quot;react-scripts start&quot;<br>},</pre><blockquote><em>- 我在 npm run dev後跑出 error，debug後發現是我使用的 node版本 18.12.0沒有支援，node 改用 16.20.2版本就可以了 😜。<br>- step1 github commit </em><a href="https://github.com/thisIsBun/build-your-own-react/commit/09d74481b0928d5d03209f68617265921da50a85"><em>連結</em></a></blockquote><h3>Step 2: The render Function</h3><p>需要寫自己的 render()，才可以要把 React element 放進 DOM。(這個步驟只有把元件加進 DOM，更動是 Step6 reconciliation)</p><h4>第一步: 建立基本架構</h4><ul><li>利用 element type和 document.createTextNode()、document.createElement() 建立 DOM node</li><li>再把 DOM node插入指定的 container</li></ul><pre>function render(element, container) {<br>  const dom =<br>    element.type === &#39;TEXT_ELEMENT&#39;<br>      ? document.createTextNode(&#39;&#39;)<br>      : document.createElement(element.type);<br> ...<br>  container.appendChild(dom);<br>}</pre><h4>第二步: 處理子元件</h4><p>因為子元件也要建立 DOM node，所以 element.props.children 裡的每個 child 用遞迴方式再次呼叫 render()</p><pre>function render(element, container) {<br> ...<br>  element.props.children.forEach((child) =&gt; render(child, dom));<br>  ...<br>}</pre><h4>第三步: 放上 props屬性</h4><p>用 filter() 找出 element.props 裡的 非 children屬性，表示是 element的 props，然後再把 props加入。</p><pre>function render(element, container) {<br>  const dom =<br>    element.type === &#39;TEXT_ELEMENT&#39;<br>      ? document.createTextNode(&#39;&#39;)<br>      : document.createElement(element.type);<br><br>  Object.keys(element.props)<br>    .filter((key) =&gt; key !== &#39;children&#39;)<br>    .forEach((key) =&gt; (dom[key] = element.props[key]));<br><br>  element.props.children.forEach((child) =&gt; render(child, dom));<br>  container.appendChild(dom);<br>}</pre><h4>第四步: 把 render 放進 Didact，呼叫 render</h4><pre>const Didact = {<br>  createElement,<br>  render,<br>};<br><br>/** @jsx Didact.createElement */<br>const element = (<br>  ...<br>);<br><br>const container = document.getElementById(&#39;root&#39;);<br>render(element, container);</pre><blockquote><em>- 這時跑 npm run dev時，應該就可以看到畫面了! (耶~~~ 😻)<br>- step2 github commit </em><a href="https://github.com/thisIsBun/build-your-own-react/commit/5ace3a8041d34f6069039d8ef350fff3c32dd8c1"><em>連結</em></a></blockquote><h3>Step 3: Concurrent Mode</h3><p>目前有個問題: 當子元件很多層時，render() 裡的遞迴處理要執行完畢，才會跑下一個操作。那這樣很可能影響到畫面互動，像是使用者點擊。</p><pre>function render(element, container) {<br>  ...<br>  element.props.children.forEach((child) =&gt; render(child, dom));<br>  container.appendChild(dom);<br>}</pre><h4>調整方式:</h4><ol><li>把任務拆分成小單位任務 unit of work</li><li>當 unit of work 完成時，讓瀏覽器檢查是否有更優先的工作需要處理 (這步驟先處理第二點。第一點會在 Step4處理。)</li></ol><h4>做法:</h4><ul><li>利用 web api requestIdleCallback(callback)，在 workLoop函式裡建立一個迴圈</li><li>利用 callback會接到的 deadline參數，用來判斷 react是否要把控制權讓給瀏覽器</li><li>要讓 requestIdleCallback() 迴圈跑起來，要先設定第一個 unit of work，然後用 performUnitOfWork() 執行</li><li>performUnitOfWork()不只要執行 unit of work，還要返回 next unit of work</li></ul><pre>let nextUnitOfWork = null;<br><br>function workLoop(deadline) {<br>  let shouldYield = false;<br>  while (nextUnitOfWork &amp;&amp; !shouldYield) {<br>    nextUnitOfWork = performUnitOfWork(nextUnitOfWork);<br>    shouldYield = deadline.timeRemaining() &lt; 1;<br>  }<br>  requestIdleCallback(workLoop);<br>}<br><br>requestIdleCallback(workLoop)<br><br>function performUnitOfWork(nextUnitOfWork) {<br>  // TODO: complete nextUnitOfWork, and return new nextUnitOfWork<br>}</pre><h4>💡 什麼是 requestIdleCallback(callback) ?</h4><ul><li>可以把 requestIdleCallback(callback) 想成 setTimeout(callback)，但不是我們指定什麼時候執行 callback，是瀏覽器有空檔的時候執行 callback</li><li>callback函式，會接到一個 deadline 參數，可以取得兩種資料: timeRemaining() 目前剩餘多少時間(ms)、didTimeout 布林值，是否超時</li></ul><blockquote><em>- 這裡是用 </em><em>requestIdleCallback() 確認瀏覽器是否有空檔執行 workLoop，但 React真正是用自己寫的 scheduler package<br>- step3 github commit </em><a href="https://github.com/thisIsBun/build-your-own-react/commit/4778951b3b29155e5cc5c78aed88207198395188"><em>連結</em></a></blockquote><h3>Step 4: Fibers</h3><p>建議先看 Pombo <a href="https://youtu.be/8Kc2REHdwnQ?si=B2x0Na8JfC4ycSFK&amp;t=540">YouTube影片</a> 說明，了解 Fiber tree的架構，也會視覺化 performUnitOfWork()、Fiber tree、DOM 執行的流程。</p><h4>說明:</h4><ul><li>延續 Step3，我們需要把任務拆成小單位任務，讓瀏覽器可以在空檔時執行小單位任務，然後執行完畢後檢查瀏覽器是否還有空檔，有的話繼續執行下一個小單位任務。</li><li>在 React裡是用 Fiber tree資料結構實現這個功能，每一個 react element都是對應一個 fiber，每個 fiber就是一個小單位任務 unit of work。</li></ul><h4>Fiber tree的關聯:</h4><ul><li>每個 child fiber 都會對應到 parent fiber</li><li>但每個 parent fiber只會對應一個 child fiber (array index=0)，剩下的是 child fiber的 sibling屬性</li></ul><h4>Fiber tree 怎麼找下一個要執行的 fiber?</h4><ul><li>fiber 是否有 child屬性 – &gt; 有的話 child就是下一個要執行的 fiber、沒有的話 fiber是否有 sibling屬性 – &gt; 有的話 sibling就是下一個要執行的 fiber</li><li>都沒有的話往 fiber 上一層找，找是否有 parent’s sibling (就是 uncle)</li><li>最後一直往上找到 root 都沒有的話，表示 fiber tree已經建立完成了</li></ul><h4>performUnitOfWork()、Fiber tree、DOM 執行的流程:</h4><ol><li>會有一個 nextUnitOfWork變數，來記錄下一個要執行的 fiber</li><li>初始化時，會從 render() 把 root指派給 nextUnitOfWork</li><li>瀏覽器有空檔時，執行 performUnitOfWork(fiber)，會依序執行下面:</li></ol><ul><li>替 fiber 產生 DOM</li><li>幫 fiber的每一個 child 產生 fiber</li><li>找出 nextUnitOfWork</li></ul><blockquote><em>step4 github commit </em><a href="https://github.com/thisIsBun/build-your-own-react/commit/d6d98fdf3a9375f03ee1d4b73e5ac1667d272e2d"><em>連結</em></a></blockquote><h3>Step 5: Render and Commit phase</h3><p>目前有個問題是，現在 DOM更新是時間點是，瀏覽器有空檔時執行 performUnitOfWork 把 fiber DOM產生出來，然後用 appendChild() 方式把 DOM放進 DOM tree產生 UI，所以使用者看到的畫面可能是不完整的。</p><h4>改分 Render 及 Commit 兩個階段更新 DOM:</h4><ul><li>刪除 performUnitOfWork裡的 appendChild()方式</li><li>利用 wipRoot 變數紀錄 fiber tree</li><li>當 performUnitOfWork沒有 nextUnitOfWork要執行時，表示 fiber tree已經建立完成了，再把 fiber tree commit到 DOM tree (覺得這好像 git flow XD)</li><li>commit有兩個分工 commitRoot() 和 commitWork():</li></ul><ol><li>commitRoot() 會觸發 commitWork()，然後清空 wipRoot</li><li>commitWork() 會遞迴的把每個 fiber放進 DOM裡</li></ol><blockquote><em>step5 github commit </em><a href="https://github.com/thisIsBun/build-your-own-react/commit/ab085e52987540248e983b29a3e691350cf6943d"><em>連結</em></a></blockquote><h3>Step 6: Reconciliation</h3><p>目前可以讓靜態畫面跑出來了，這個步驟要實現動態畫面操作。</p><p>為了確認程式碼沒問題，先把 react element改成輸入框，h2可以出現打字內容就成功了。</p><pre>/** @jsx Didact.createElement */<br>const container = document.getElementById(&quot;root&quot;);<br>const updateValue = (e) =&gt; {<br>  rerender(e.target.value);<br>};<br><br>const rerender = (value) =&gt; {<br>  const element = (<br>    &lt;div&gt;<br>      &lt;input onInput={updateValue} value={value} /&gt;<br>      &lt;h2&gt;Hello {value}&lt;/h2&gt;<br>    &lt;/div&gt;<br>  );<br>  Didact.render(element, container);<br>};<br><br>rerender(&quot;World&quot;);</pre><h4>比較新舊 Fiber tree的 Reconciliation機制:</h4><ul><li>需要有方式比較新舊 fiber tree，React把這個比較的機制叫做 Reconciliation</li><li>新增變數 currentRoot，用來存目前畫面的 fiber tree</li><li>fiber新增 alternate 屬性: 用來紀錄上一次 render的 fiber</li><li>fiber新增 effectTag 屬性: 用來標記跟上一次 render比較後的結果，分三種 tag:</li></ul><ol><li>UPDATE: 表示 DOM要保留但 props內容要更新</li><li>PLACEMENT: 表示是新 DOM</li><li>DELETION: 表示 DOM要刪除</li></ol><h4>流程:</h4><ul><li>新增 reconcileChildren函式，會從 performUnitOfWork取得 wipFiber 和 children，用 oldFiber 和 wipFiber的 type判斷要給哪種 effectTag</li><li>調整 commitWork函式:</li></ul><ol><li>effectTag=’PLACEMENT’，新 DOM 處理方式跟之前一樣</li><li>effectTag=’DELETION’，表示 DOM 需要刪除</li><li>effectTag=’UPDATE’，表示 DOM 裡的 props 內容需要更新，更新動作會在 updateDom函式操作</li></ol><ul><li>新增 updateDom函式，處理新舊 props、處理新舊 event</li><li>另外 createDom、commitRoot、render、performUnitOfWork 做應對調整後，輸入框輸入的字就可以在 h2 看到了耶✌️</li></ul><blockquote><em>step6 github commit </em><a href="https://github.com/thisIsBun/build-your-own-react/commit/d7ea5d2730591e1117f176f1b2549406f2843aa7"><em>連結</em></a></blockquote><h3>Step 7: Function Components</h3><p>目前 react element寫法，還沒有支援比較常撰寫的 function components，所以這個步驟要來完成。(寫完這段有更了解 function components喔！)</p><p>先把 react element改成 function component:</p><pre>/** @jsx Didact.createElement */<br>function App(props) {<br>  return &lt;h1&gt;Hi {props.name}&lt;/h1&gt;<br>}<br>const element = &lt;App name=&quot;foo&quot; /&gt;<br>const container = document.getElementById(&quot;root&quot;)<br>Didact.render(element, container)</pre><p>可以注意 function components 在 jsx 轉成 js 有兩點不同:</p><ol><li>fiber.type 可能是 function，像下面 App 是函式</li><li>子元件是要執行函式後，return 值取得</li></ol><pre>function App(props) {<br>  return Didact.createElement(<br>    &quot;h1&quot;,<br>    null,<br>    &quot;Hi &quot;,<br>    props.name<br>  )<br>}<br>const element = Didact.createElement(App, {<br>  name: &quot;foo&quot;,<br>})</pre><p>所以要做下面調整:</p><ul><li>調整 performUnitOfWork函式，用 fiber.type判斷 fiber是否是函式: 是的話執行 updateFunctionComponent、不是的話執行 updateHostComponent，執行內容跟之前一樣</li><li>新增 updateFunctionComponent: fiber.type是函式，所以 children 是需要執行 fiber.type 取得。需帶入 fiber.props當參數，children是陣列所以需用 [] 包起來。</li><li>調整 commitWork函式，需增加兩個判斷:</li></ul><ol><li>當要把 fiber append到父層 dom時， 如果父層 dom不存在，會一直往上找直到找到父層 dom為止</li><li>當要把 fiber刪除時，觸發 commitDeletion函式，當要把 fiber刪除時，會一直往下找直到找到 child有 dom為止</li></ol><blockquote><em>step7 github commit </em><a href="https://github.com/thisIsBun/build-your-own-react/commit/92ea0f690b3a5878d6f3409f9209ca15350b391f"><em>連結</em></a></blockquote><h3>Step 8: Hooks</h3><p>build your own React 最後一步，實現 useState hooks!</p><p>先把 element改成有使用 useState，每點擊 h1 數字就會+1:</p><pre>const Didact = {<br>  ...<br>  useState,<br>};<br><br>/** @jsx Didact.createElement */<br>function Counter() {<br>  const [state, setState] = useState(1);<br>  return &lt;h1 onClick={() =&gt; setState((c) =&gt; c + 1)}&gt;Count: {state}&lt;/h1&gt;;<br>}<br>const element = &lt;Counter /&gt;;</pre><h4>做法:</h4><ol><li>新增 wipFiber, hookIndex全域變數，用來存 function components fiber的資料，讓 useState可以使用</li><li>調整 updateFunctionComponent函式</li></ol><ul><li>把 fiber指派給 wipFiber、hookIndex值初始為 0</li><li>wipFiber新增 hooks屬性，用來存同一個 component裡多次觸發的 useState</li><li>新增 useState函式</li></ul><h4>useState函式</h4><ul><li>接受一個 initial 參數</li><li>利用 fiber alternate屬性，找上一次 render時是否有 old hooks資料，有的話存在 oldHooks 變數</li><li>新增一個 hook物件，用來存目前 render的 hook資料，有兩個屬性 state 和 queue:</li></ul><ol><li>state 初始值是來自於 oldHooks 或 initial，目前的 state值是從 queue裡的 action執行後取得。</li><li>queue 初始值是空陣列，會在 function component觸發 setState 時把 action存進 queue。</li></ol><ul><li>新增 setState 函式: 主要有兩個工作，第一是把 action存進 queue，第二步是觸發 re-render</li><li>把更新的 hook存進 wipFiber.hoos，hookIndex++</li><li>最後 return 一個陣列，第一個值是目前 state、第二個值是 setState function</li></ul><blockquote><em>step8 github commit </em><a href="https://github.com/thisIsBun/build-your-own-react/commit/684c71101234c4f18ac098348d51ac05388c40d1"><em>連結</em></a></blockquote><h3>參考</h3><ul><li>Pombo build your own React文章: <a href="https://www.sytone.me/build-your-own-react">https://www.sytone.me/build-your-own-react</a></li><li>Pombo YouTube說明 build your own React: <a href="https://www.youtube.com/watch?v=8Kc2REHdwnQ">https://www.youtube.com/watch?v=8Kc2REHdwnQ</a></li><li>了解 JSX怎麼用 babel轉成 React.createElement: <a href="https://react.dev/reference/react/createElement">https://react.dev/reference/react/createElement</a></li><li>babel官網，說明用註解方式客製名稱 <a href="https://babeljs.io/docs/babel-plugin-transform-react-jsx#customizing-the-classic-runtime-import">https://babeljs.io/docs/babel-plugin-transform-react-jsx#customizing-the-classic-runtime-import</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=30bca582344a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>