instanceof অপারেটর পরীক্ষা করে কনস্ট্রাক্টরের prototype প্রপার্টি কোনো অবজেক্টের প্রোটোটাইপ চেইনে কোথাও উপস্থিত আছে কিনা। সহজ ভাষায়, এটি পরীক্ষা করে কোনো ভেরিয়েবল নির্দিষ্ট টাইপের কিনা। কিন্তু এর কিছু সতর্কতা আছে। চলুন কিছু উদাহরণ দেখি।
প্রাইমিটিভস
স্ট্রিং এবং নম্বর প্রাইমিটিভ মান, অবজেক্ট নয় এবং তাই [[Prototype]] থাকে না, তাই এটি শুধু কাজ করবে যদি আপনি সেগুলোকে রেগুলার অবজেক্টে র্যাপ করেন।
উদাহরণ
console.log(1 instanceof Number) console.log(new Number(1) instanceof Number) console.log("" instanceof String) console.log(new String("") instanceof String)আউটপুট
false true false true
কনস্ট্রাক্টিবল ফাংশন
যে ফাংশনগুলো তাদের অবজেক্ট রিটার্ন করে (জেএস ক্লাস), তাদের অবজেক্টগুলো instanceof অপারেটর দিয়ে চেক করা যায়।
উদাহরণ
function Person(name) { this.name = name } let john = new Person("John"); console.log(john instanceof Person)আউটপুট
true
ইনহেরিটেন্স
জেএস প্রোটোটিপিক্যাল ইনহেরিটেন্স সাপোর্ট করে, তাই আপনি হায়ারার্কিতে যেকোনো ক্লাসের জন্য instanceof চেক করলে true রিটার্ন করবে।
উদাহরণ
class Person {} class Student extends Person { constructor(name) { super() this.name = name } } let john = new Student("John"); console.log(john instanceof Person) console.log(john instanceof Student)আউটপুট
true true