Skip to content

Instantly share code, notes, and snippets.

@ToQoz
Created November 21, 2011 02:20
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ToQoz/1381425 to your computer and use it in GitHub Desktop.
Save ToQoz/1381425 to your computer and use it in GitHub Desktop.
typeof と instanceof について

typeof

有用なとき

typeof foo !== 'undefined'

有用でないとき

上記以外.

[上記以外が有用でない理由]

typeofの戻り値は仕様で定義されていないものを返します。よって、実装によって別の結果になる事がある 例えば,

1.2 => Class:Number Type:number

new Number(1.2) => Class Number Type:object

オブジェクトの型をチェックする為には、

function is(type, obj) {
    var clas = Object.prototype.toString.call(obj).slice(8, -1);
    return obj !== undefined && obj !== null && clas === type;
}

is('String', 'test'); // true
is('String', new String('test')); // true

instanceof

有用なとき

カスタムで作ったオブジェクトを比較する時にのみ。function Foo() {}

function Bar() {};
new Bar() instanceof Bar; // true

有用でないとき

組み込み型

new String('foo') instanceof String; // true
new String('foo') instanceof Object; // true

'foo' instanceof String; // false
'foo' instanceof Object; // false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment