JavaScript instanceof 運算符 - 它的作用,如何使用它
本文將解釋 JavaScript instanceof 運算符以及如何使用它。提供示例。
什麼是instanceof 做什麼?
實例 運算符返回 TRUE 或 FALSE,具體取決於給定值或變量是否屬於特定類型 或類 – 它檢查一個值是否是一個實例 給定的對像類或類型。
instanceof 的用途 可能看起來令人困惑 - 您已經有 typeof ,那麼您需要什麼instanceof 為了?
類型 將簡單地返回一個包含變量類型或類名稱的字符串。相比之下,instanceof 將返回一個布爾值,以確認給定變量是否在編程級別與給定類匹配。
什麼是類型/類?
變量類型 確定它可以存儲什麼樣的數據以及可以為它做什麼。變量類型由其類定義 – 這是定義可以存儲哪些數據以及功能和相關行為的代碼。
例如,字符串 類型化變量是可以連接和拆分的字符序列(想想單詞和句子 ),而數值類型變量包含可用於算術的數值。
實例 語法
使用 instanceof 的語法 如下:
OBJECT instanceof CONSTRUCTOR
注意:
- 對象 是您要檢查的變量或值
- 建設者 是您要檢查 OBJECT 的類的名稱 是 的一個實例
- 將返回布爾值 TRUE 或 FALSE
- 實例 檢查 OBJECT
- 的整個原型鏈
- 這意味著 instanceof 可以為兩個不同的 CONSTRUCTOR 返回一個肯定的結果 s 如果一個構造函數派生自另一個構造函數
實例 JavaScript 示例
此示例創建一個 Person 類,然後使用該類創建一個對象。 實例 然後用於確認創建的對像是否屬於 Person 類。
// Define a constructor which creates an object of the Person class - containing a person's details function Person(name, age, height) { this.name = name; this.age = age; this.height = height; } // Define a new person using the above constructor var jim = new Person('Jim', 21, 182); // Check whether the jim variable is an instance of the Person class console.log(jim instanceof Person); // Will return true as jim is an instance of the Person class // Check whether the jim variable is of the Object class console.log(jim instanceof Object); // Will also return true - JavaScript objects are an inheritable class which other objects are built on console.log(jim instanceof String); // Will return false as the jim variable is not of the String type
請注意,jim 對像被視為 Person 的實例 和對象 類 – 作為 Person 類擴展了 Object 班級。在大多數情況下,JavaScript 中的自定義類在創建時會擴展 Object 類,除非另有說明。
有關如何使用 instanceof 的更多示例,請查看 Mozilla 開發人員文檔。