typeof と instanceof の違いは何ですか? また、どちらをいつ使用すべきですか? 質問する

typeof と instanceof の違いは何ですか? また、どちらをいつ使用すべきですか? 質問する

私の場合:

callback instanceof Function

または

typeof callback == "function"

それは重要ですか、違いは何ですか?

追加リソース:

JavaScriptガーデンインスタンス

ベストアンサー1

instanceofカスタムタイプに使用:

var ClassFirst = function () {};
var ClassSecond = function () {};
var instance = new ClassFirst();
typeof instance; // object
typeof instance == 'ClassFirst'; // false
instance instanceof Object; // true
instance instanceof ClassFirst; // true
instance instanceof ClassSecond; // false 

typeofシンプルな組み込み型に使用します:

'example string' instanceof String; // false
typeof 'example string' == 'string'; // true

'example string' instanceof Object; // false
typeof 'example string' == 'object'; // false

true instanceof Boolean; // false
typeof true == 'boolean'; // true

99.99 instanceof Number; // false
typeof 99.99 == 'number'; // true

function() {} instanceof Function; // true
typeof function() {} == 'function'; // true

instanceof複雑な組み込み型に使用します:

/regularexpression/ instanceof RegExp; // true
typeof /regularexpression/; // object

[] instanceof Array; // true
typeof []; //object

{} instanceof Object; // true
typeof {}; // object

最後のはちょっと難しいです:

typeof null; // object

おすすめ記事