Course contentsShow
← JavaScript
Lesson 739 of 2,72317. Prototypes and InheritanceFree lesson

instanceof Across Realms and Frames

Learn why instanceof can fail when objects come from different execution contexts or iframes.

instanceof Across Realms and Frames

You'll learn why instanceof can give unexpected false results when objects come from different JavaScript execution contexts like iframes or separate realms.

The Problem with Multiple Execution Contexts

When you work with iframes, Web Workers, or separate VM contexts (called "realms"), each one has its own separate copy of built-in constructors like Array, Object, and Date. Even though they work identically, they're technically different constructor functions with different prototype objects.

Here's the issue: instanceof checks if an object's prototype chain contains a specific constructor's prototype property. When an array is created in an iframe, its __proto__ points to the iframe's Array.prototype — not your main page's Array.prototype.

Why This Breaks instanceof

// In main page:
const iframe = document.createElement('iframe');
document.body.appendChild(iframe);

// Create an array INSIDE the iframe
const iframeArray = iframe.contentWindow.Array(1, 2, 3);

// This fails!
console.log(iframeArray instanceof Array);  // false
// Because iframeArray's __proto__ is iframe's Array.prototype
// Not the main window's Array.prototype

// But this works:
console.log(Array.isArray(iframeArray));  // true

The Solution

Use type-specific methods like Array.isArray() or check the object's internal type with Object.prototype.toString.call(obj). These methods are designed to work across realms.

Key Takeaway: instanceof fails across iframes and realms because each execution context has its own separate copy of constructor functions and prototypes — use Array.isArray() or similar methods for reliable cross-realm type checking.