typeof、instanceof与isPrototypeOf()的差异与联系

一、typeof

1.typeof的意义及作用:

  我们知道ECMAScript中有5种简单(基本)数据类型:Undefined、Null、Boolean、Number、String,以及一种引用数据类型Object。typeof的作用正式用于判断操作数的数据类型的。所有的返回值为以上六种数据类型之一。

2.typeof操作符有下面两种用法:

  1. typeof 操作数
  2. typeof (操作数)

3. typeof中的陷阱

  • typeof null 会返回 “object”,因为特殊值null被认为是一个空的对象引用。
  • 正则表达式在不同浏览器中返回值不同,具体如下
1 typeof /s/ === 'function'; // Chrome 1-7... // 不符合 ECMAScript 5.1
2 typeof /s/ === 'object'; // Firefox 5+ 、Chrome 7+...    // 符合 ECMAScript 5.1

4. 测试例子

 1 // Numbers
 2 typeof 37 === 'number';
 3 typeof 3.14 === 'number';
 4 typeof Math.LN2 === 'number';
 5 typeof Infinity === 'number';
 6 typeof NaN === 'number'; // 尽管NaN是"Not-A-Number"的缩写,意思是"不是一个数字"
 7 typeof Number(1) === 'number'; // 不要这样使用!
 8 
 9 // Strings
10 typeof "" === 'string';
11 typeof "bla" === 'string';
12 typeof (typeof 1) === 'string'; // typeof返回的肯定是一个字符串
13 typeof String("abc") === 'string'; // 不要这样使用!
14 
15 // Booleans
16 typeof true === 'boolean';
17 typeof false === 'boolean';
18 typeof Boolean(true) === 'boolean'; // 不要这样使用!
19 
20 // Undefined
21 typeof undefined === 'undefined';
22 typeof blabla === 'undefined'; // 一个未定义的变量,或者一个定义了却未赋初值的变量
23 
24 // Objects
25 typeof {a:1} === 'object';
26 typeof [1, 2, 4] === 'object'; // 使用Array.isArray或者Object.prototype.toString.call方法可以分辨出一个数组和真实的对象
27 typeof new Date() === 'object';
28 
29 typeof new Boolean(true) === 'object' // 令人困惑.不要这样使用
30 typeof new Number(1) === 'object' // 令人困惑.不要这样使用
31 typeof new String("abc") === 'object';  // 令人困惑.不要这样使用
32 // Functions
33 typeof function(){} === 'function';
34 typeof Math.sin === 'function';

二、instanceof

1.typeof的意义及作用:

  instanceof运算符可以用来判断某个构造函数的prototype属性是否存在另外一个要检测对象的原型链上.关于原型链的知识在new和instanceof的内部机制JavaScript中__proto__与prototype的关系中已做了讲解。

2.instanceof中的陷阱:

  在浏览器中,我们的脚本可能需要在多个窗口之间进行交互.多个窗口意味着多个全局环境,不同的全局环境拥有不同的全局对象,从而拥有不同的内置类型构造函数.这可能会引发一些问题.比如,表达式[] instanceof window.frames[0].Array会返回false,因为 Array.prototype !==window.frames[0].Array.prototype,因此你必须使用 Array.isArray(myObj)或者 Object.prototype.toString.call(myObj) === "[object Array]"来判断myObj是否是数组.

三、isPrototypeOf

1.typeof的意义及作用:

  检测一个对象是否存在于另一个对象的原型链中.其作用与instanceof有点相似,但使用方法是不一样的。

2.用法与例子:

 1 function Fee() {
 2   // . . .
 3 }
 4 
 5 function Fi() {
 6   // . . .
 7 }
 8 Fi.prototype = new Fee();
 9 
10 function Fo() {
11   // . . .
12 }
13 Fo.prototype = new Fi();
14 
15 function Fum() {
16   // . . .
17 }
18 Fum.prototype = new Fo();
19 
20 var fum = new Fum();
21 . . .
22 
23 Fi.prototype.isPrototypeOf(fum); //true
24 fum instanceof Fi; // true
原文地址:https://www.cnblogs.com/WhiteCusp/p/3667437.html