ใช่ คุณสามารถใช้แนวคิดของคลาสได้ หากคุณต้องการตรวจสอบประเภทข้อมูลจริง คุณสามารถใช้ Instanceof ได้
อินสแตนซ์ของบอกเกี่ยวกับประเภทข้อมูล นี่คือตัวอย่างโค้ด JavaScript ซึ่งจะให้คำอธิบายสั้น ๆ เกี่ยวกับวิธีการสร้างชนิดข้อมูลใหม่และวิธีการตรวจสอบชนิดข้อมูล ที่นี่ ฉันจะให้การใช้งานแบบกำหนดเองเพื่อตรวจสอบประเภทข้อมูล
ตัวอย่าง
ต่อไปนี้เป็นรหัส -
//creating the class
class Game {
constructor(gameName) {
this.gameName = gameName;
}
}
//creating an object
const ticTacToe = new Game("TicTacToe");
// checking the data type.
function dataTypeBelongsTo(object) {
if (object instanceof Game)
return "Game";
return typeof object;
}
console.log("The ticTacToe is the object of Game class=" + (ticTacToe instanceof Game));
console.log("The data Type of ticTacToe is =" + dataTypeBelongsTo(ticTacToe));
console.log("The data Type Candy Cash is =" + dataTypeBelongsTo("Cady Cash")); ในการรันโปรแกรมข้างต้น คุณต้องใช้คำสั่งต่อไปนี้ -
node fileName.js.
ที่นี่ ชื่อไฟล์ของฉันคือ demo288.js
ผลลัพธ์
สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้บนคอนโซล -
PS C:\Users\Amit\javascript-code> node demo288.js The ticTacToe is the object of Game class=true The data Type of ticTacToe is =Game The data Type Candy Cash is =string