Перейти к основному содержимому
← ⚡ JavaScript & the browser·Модуль C5 · Урок 4
ЗаданиеWrite show(x): Date → ISO string, Error → "ERR: <message>", everything else → String(x). Log show(new Date(0)), show(new TypeError("boom")), show(42), show("hi").

instanceof for Date and custom classes

100 XP8 min
Теория

What instanceof tests

x instanceof Constructor returns true if x was made with new Constructor() (or a subclass). It's the type guard for class-based values like Date, Error, Map, Set, or your own classes.

const d = new Date();
d instanceof Date;       // true

const err = new TypeError("x");
err instanceof TypeError; // true
err instanceof Error;     // true  (TypeError extends Error)
err instanceof Date;      // false

class User { constructor(name) { this.name = name; } }
new User("Anna") instanceof User; // true

Common pattern: handle Date, Error, or plain text

function show(x) {
  if (x instanceof Date)  return x.toISOString();
  if (x instanceof Error) return "ERR: " + x.message;
  return String(x);
}

Versus typeof

typeof new Date() returns "object". Useless. instanceof Date is the actual answer.

🔒

Зарегистрируйся чтобы кодить

Теория открыта всем. Интерактивный редактор, живой превью и проверка открываются с 7-дневным бесплатным trial — нужна карта, отмена в любое время.

Регистрация — бесплатный trial →

Первые 10 уроков в каждом треке — бесплатные. Карта не нужна.

← НазадСледующий урок →

Получай один совет по Python или веб-разработке — каждый день в почте

Коротко, без воды, без спама. Отписаться — в один клик.