LoginSignup
0
0

More than 1 year has passed since last update.

instanceofについてメモ(処理の切り替え)[JavaScript]

Posted at

instanceofについてのメモ。

instanceof

instanceof 演算子は、オブジェクトが自身のプロトタイプにコンストラクタの prototype プロパティを持っているかを確認します。戻り値はブール値です。

どのコンストラクターから生成されたオブジェクトかを確認することができる。

構文

object instanceof constructor

使用例

オブジェクトによって処理を切り替えたいとき

function fn(arg) {
    // 配列とオブジェクトでは値の設定の仕方が変わる
    // 渡ってきたインスタンスの種類によって処理を切り替える
    if(arg instanceof Array) {
        arg.push('value');
    } else {
    arg['key'] = 'value';
    }
    console.log(arg);
}

fn({});

参考・引用

instanceof - JavaScript | MDN

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0