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
カスタムで作ったオブジェクトを比較する時にのみ。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