LoginSignup
2
2

More than 5 years have passed since last update.

Javascriptのconstructorを比較するときは文字列じゃない!

Last updated at Posted at 2015-01-27
var a = new Array;
if (a.constructor == "Array") {
    console.log("Array だよ");
} else {
    console.log("Array じゃないよ");
}
/*
出力結果
Array じゃないよ
*/

的なのに、激ハマリしたのでなんとなくまとめてみた。
正しくは、クォートを外して。

var a = new Array;
if (a.constructor == Array) {
    console.log("Array だよ");
} else {
    console.log("Array じゃないよ");
}
/*
出力結果
Array だよ
*/

typeofと混同注意ということですね。
以下、適当にまとめてみた。

function Animal(name){
    this.name = name;
}

var dog = new Animal("dog");

console.log(dog);
/*
出力結果 関数のコードが出力される。
function Animal(name){
    this.name = name;
}
*/

//けど…組み込み系はこーなる
var ary = new Array();
console.log(ary);

/*
function Array() { [native code] }
*/

//クラスの判定に使える
if (dog.constructor === Animal) { //クォートとかいらないマジイラナイ!!
    console.log("dog is Animal");
}

/* 他に instanceofを使用 */
if (dog instanceof Animal) { //これもクォートいらない
    console.log("dog is Animal");
}

//dogのconstructor Animalで作成
var bird = new dog.constructor("bird");

//クラス名を表示
console.log(dog.constructor.name);

2
2
2

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
2
2