instanceof Operator
instanceof
tests whether the prototype chain of a value contains the prototype
of a given constructor (function or class).
It returns true/false and works only for objects (not primitives), unless custom logic is provided via Symbol.hasInstance
.
Syntax
expression instanceof Constructor
Examples
// ১) ক্লাস/ইনহেরিটেন্স
শ্রেণী প্রাণী {}
শ্রেণী কুকুর প্রসারিত প্রাণী {}
const d = নতুন কুকুর();
কনসোল.লগ(d উদাহরণ_হিসেবে কুকুর); // true
কনসোল.লগ(d উদাহরণ_হিসেবে প্রাণী); // true
কনসোল.লগ(d উদাহরণ_হিসেবে Object); // true
// ২) ফাংশন কন্সট্রাক্টর
function User() {}
const u = নতুন User();
কনসোল.লগ(u উদাহরণ_হিসেবে User); // true
// ৩) বিল্ট‑ইন
কনসোল.লগ([] উদাহরণ_হিসেবে Array); // true
কনসোল.লগ((new Date()) উদাহরণ_হিসেবে Date); // true
কনসোল.লগ(/re/ উদাহরণ_হিসেবে RegExp); // true
// ৪) প্রিমিটিভে কাজ করে না
কনসোল.লগ(("hi") উদাহরণ_হিসেবে String); // false
কনসোল.লগ((42) উদাহরণ_হিসেবে Number); // false
কনসোল.লগ((true) উদাহরণ_হিসেবে Boolean); // false
কনসোল.লগ((null) উদাহরণ_হিসেবে Object); // false
কনসোল.লগ((undefined) উদাহরণ_হিসেবে Object); // false
// ৫) কাস্টম নিয়ম — Symbol.hasInstance
শ্রেণী জোড়সংখ্যা {
স্থির [Symbol.hasInstance](x) {
ফেরত (ধরন x === "number") && x % 2 === 0;
}
}
কনসোল.লগ(42 উদাহরণ_হিসেবে জোড়সংখ্যা); // true
কনসোল.লগ(7 উদাহরণ_হিসেবে জোড়সংখ্যা); // false
Notes
instanceof
walks the prototype chain; it does not compare constructors directly.- Works only on objects. For primitives, prefer
typeof
. Wrapper objects (new String("x")
) are generally discouraged. - Cross‑realm (iframes, vm contexts) mean different constructors;
x instanceof Array
may befalse
. PreferArray.isArray(x)
for arrays. - You can customize behavior via
static [Symbol.hasInstance](value)
on a constructor. - For structural checks, use duck typing or schema validation instead of
instanceof
.