簡體   English   中英

是否可以使用更短的助手 function 而不是 typeof something?== "undefined"?

[英]Is it possible to use a shorter helper function instead of typeof something !== "undefined"?

這很好用

var isRenderer = typeof process !== "undefined" && process.type === "renderer";

我不喜歡在我的代碼中進行這些 typeof 檢查,所以我嘗試編寫一個 helper function。但是使用它會導致引用錯誤被拋出

var isRenderer = !isUndefined(process) && process.type === "renderer";

function isUndefined(val) {
  return typeof val === "undefined";
}

我有兩個問題:

  • 為什么我寫的助手function不起作用?
  • 是否可以編寫一個幫助程序 function 來替換 typeof 檢查?

我不喜歡在我的代碼中進行這些 typeof 檢查,所以我嘗試編寫一個 helper function。但是使用它會導致引用錯誤被拋出

如果您的 function 出錯,這告訴我們process是一個未聲明的標識符,而不僅僅是一個值為undefined的變量/參數。 您可以對未聲明的標識符使用typeof ,但無法讀取其值。

不幸的是,您不能編寫 function 來執行您概述的操作。 最接近的是:

var isRenderer = !isUndefined(typeof process) && process.type === "renderer";

function isUndefined(type) {
  return type === "undefined";
}

請注意,在您調用它的地方它仍然需要typeof 但至少如果您在"undefined"中有錯字(就像我經常做的那樣),它至少可以避免出現無聲邏輯錯誤的機會。

最好的方法是查看您嘗試使用未聲明標識符的原因並解決這些問題。 但是除非這樣做,否則您將需要typeof檢查。


如果process是聲明的標識符但它的值為undefined ,則您的 function 會起作用。 但在那種情況下,由於可選鏈,您很快就不需要它了。 這是 ES2020 規范中的一項新功能,適用於現代 JavaScript 環境(Chrome v80+、Firefox v74+、Safari 13.1+),如果您轉譯(例如,使用 Babel),則可以與舊的 JavaScript 環境一起使用。 然后你的陳述看起來像這樣:

// ONLY WORKS IF `process` IS DECLARED
var isRenderer = process?.type === "renderer";

如果聲明了process但其值為undefinednull ,則isRenderer將為false ,因為process?.type的計算結果為undefined ,而undefined === "renderer"為 false。

但同樣,這在您遇到的情況下不起作用,因為process是未聲明的標識符。

正如已經回答和評論的那樣,您不能將未聲明的變量傳遞給 function 而不會在嘗試讀取變量以將其作為參數傳遞時生成錯誤。

但是,如果processnull ,則在檢查其屬性之前簡單地檢查該process是否已定義會失敗。 我通常使用並建議的解決方案是檢查 object 值,然后檢查它不是null

if(typeof process === "object" && process && process.type === "renderer") 

一般比較安全。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM