---
title: "typeof与instanceof "
author: "cxy020"
date: "2011-10-11T11:03:12Z"
tags: ["instanceof", "typeof"]
categories: ["Web前端"]
slug: "typeof-instanceof"
draft: false
lastmod: "2011-10-11T11:03:12Z"
id: 1189400
url: "https://cxy020.iteye.com/blog/1189400"
---

typeof 返回对象数据类型，总共有6种返回结果
"number"，"string"，"boolean"，"object"，"function"，"undefined"
语法： typeof "a" == "string"
      typeof  [] == "object"


instanceof 判断对象是否是特定类的一个实例，返回一个 Boolean 值。

语法： var a = new String("ss");
      a instanceof String == true
      [] instanceof Array == true
但是 "sss" instanceof String == false, 为什么呢，个人认为有两个原因
1.通过typeof 知道  typeof new String("ss") == "object", 
而typeof "ss" == "string"
2.instanceof 是判断对象

在实际开发中，我们通常使用typeof来判断一个变量是否存在。
如if(typeof a!="undefined"){}，而不要去使用if(a)，因为如果a不存在（未声明）则会出错。
但是对于Array,Null等特殊对象使用typeof一律返回object，这正是typeof的局限性。

我们通常使用instanceof来判断对象是否是数据，或者是否是某一个对象的实例。
如var a=new Array();a instanceof Array == true，
var a = new Object(); a instanceof Array == false。
再如：function test(){};var a=new test();a instanceof test == true。


但是js也有特列，看起来像数组或对象却实际上又不是。
如：function的arguments，arguments看起来是一个Array，但如果使用instaceof去测试会发现arguments不是一个Array对象。 
如：window instanceof Object， 这个在IE7里面会返回false,但是在ff里面返回的却是true。

