ได้ ใช้ class สร้างชนิดข้อมูลใหม่ และ instanceof ตรวจสอบชนิด
ตัวอย่างโค้ด
// สร้าง class
class Game {
constructor(gameName) {
this.gameName = gameName;
}
}
// สร้างอ็อบเจ็กต์
const ticTacToe = new Game("TicTacToe");
// ตรวจสอบชนิดข้อมูล
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
คำอธิบาย: class สร้าง blueprint สำหรับอ็อบเจ็กต์ instanceof ตรวจสอบ prototype chain ว่าอ็อบเจ็กต์สร้างจาก class นั้นหรือไม่ typeof ใช้สำหรับ primitive types