2025年2月24日 星期一

初探 Function.toString()

 初探 Function.toString()

前言

  最近發現 JavaScript 可以在執行的時候,透過 Function.toString() 來返回原始碼,在此把學習的過程做個紀錄。


內容

  範例如下

function myCall(){
  //comment...
  
  return 1234;
}
//
console.log( myCall.toString() );
// "function myCall(){
//   //comment...
  
//   return 1234;
// }"


可以看到 Function.toString() 的結果會是該 Function 的原始碼,比較特別的是返回的原始碼裡不論是空白換行與註解都會完整地返回,雖然不知道這個功能有什麼實用的地方,但還是個有趣的功能。


參考資料

[ developer.mozilla.org ] Function.prototype.toString()

2025年2月17日 星期一

初探 Nullish coalescing assignment (??=)

 初探 Nullish coalescing assignment  (??=)

前言

  在先前的 初探 Nullish coalescing operator (??) 介紹過 ?? ,這次來學習跟它很像的 ??=  ,在此把學習的過程做個紀錄。


內容

  範例如下

let obj = {
  a : 1234
};
//
obj.a ??= 5678;
console.log( obj.a );//1234
//
obj.b ??= 9999;
console.log( obj.b );//9999
//
obj.c ??= undefined;
console.log( obj.c );//undefined
//
obj.d ??= null;
console.log( obj.d );//null


??= 是有賦值的特性,並不是像 == 之類比較,賦值的邏輯是當左側是 null 或 undefiend 則給予賦值,範例第一例由於 a 已經有數值,所以賦值不會成功, b 由於本來就沒值,所以賦值成功,如果左側原本沒值,右側賦予 null 或 undefined 會成功嗎?從 c 與 d 的結果來看答案是肯定的!


參考資料

[ developer.mozilla.org ] Nullish coalescing assignment (??=)


相關文章與資料

初探 Nullish coalescing operator (??)

2025年2月10日 星期一

初探 Nullish coalescing operator (??)

 初探 Nullish coalescing operator (??)

前言

  最近發現新語法 Nullish coalescing operator ,在此把學習的過程做個紀錄。


內容

  範例如下

console.log( 1111 ?? undefined );//1111
console.log( null ?? 1234);//1234
console.log( null ?? undefined ?? 5678);//5678
console.log( null ?? 'abcd' ?? undefined);//"abcd"
console.log( null ?? 5555 ?? undefined ?? 9999);//5555


Nullish coalescing operator 可以理解成處理的雙方只要有一方不是 null 或 undefined ,還可以連續處理多個對象,如範例的第三、第四與第五例,要注意處理都是左方對象優先,第五例回傳的是 5555 而非 9999。


參考資料

[ developer.mozilla.org ] Nullish coalescing operator (??)

2025年2月3日 星期一

初探 Optional chaining (?.)

 初探 Optional chaining (?.)

前言

  最近發現 JavaScript 有個 Optional chaining 的語法,在此把學習的過程做個紀錄。


內容

  範例如下

const adventurer = {
  name: 'Alice',
  cat: {
    name: 'Dinah'
  }
};
const dogName = adventurer?.name;
//Follow code has the same result...
//const dogName = adventurer.dog && adventurer.dog.name;
console.log(dogName);//Alice
//
const catName = adventurer?.cat?.name;
console.log(catName);//Dinah


Optional chaining  用來簡化程式碼,在寫程式常常需要檢查物件是否存在,若存在提取其內容這樣的邏輯,用 ?. 的語法就可以快速完成,範例的 dogName 會先確認 adventurer 是否存在,若存在回傳 aadventurer.name ,若不存在則是回傳 undefined ,這點要注意。這個語法還可以使用在巢狀結構,如範例的 catName 的應用,先確認 adventurer  是否存在,再確認 adventurer.cat 的存在,都沒問題才回傳 adventurer.cat.name 。


參考資料

[ developer.mozilla.org ] Optional chaining (?.)