#
ドキュメント

Document

自分のための備忘録です。

型・コンストラクタを判別

  • 型を示す:typeof
  • コンストラクタを示す:constructorプロパティを使用
    • index.htmlconstructorプロパティを参照
  • コンストラクタのインスタンスかを判別する:instanceof

型を示す

console.log(typeof 42);
// expected output: "number"

console.log(typeof 'blubber');
// expected output: "string"

console.log(typeof true);
// expected output: "boolean"

console.log(typeof undeclaredVariable);
// expected output: "undefined"

引用元:https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Operators/typeof

コンストラクタを示す

/*
 * constructorでコンストラクタを示す
 */
// DOM
const element = document.querySelector('div');
element.constructor; // HTMLDivElement

// カスタムオブジェクト
class Hoge {
}
let hoge = new Hoge();
hoge.constructor; // Hoge() {}

コンストラクタのインスタンスかを判別する

function Car(make, model, year) {
  this.make = make;
  this.model = model;
  this.year = year;
}
const auto = new Car('Honda', 'Accord', 1998);

console.log(auto instanceof Car);
// expected output: true

console.log(auto instanceof Object);
// expected output: true

引用元:https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Operators/instanceof

ref. https://ja.javascript.info/instanceof