码迷,mamicode.com
首页 > 其他好文 > 详细

typeof 和instanceof

时间:2017-02-25 22:40:21      阅读:188      评论:0      收藏:0      [点我收藏+]

标签:存在   bool   null   java   它的   测试   string   运算   ber   

1.typeof

首先来看typeof的测试结果

 1 //1.typeof 判定 非构造函数 数据类型    
 2 var a = ‘123‘;        //typeof a === string
 3 var b = 123;          //typeof b === number
 4 var c = true;          //typeof c === boolean
 5 var d = function(){};//typeof d === function
 6 var e = {};             //typeof e === object
 7 var f = undefined;     //typeof f === undefined
 8 var g = null;         //typeof g === object
 9 var h = ‘‘;             //typeof h === string
10 var i;                 //typeof i === undefined
11 var j = [];             //typeof j === object
12 结论:typeof 判定非构造函数数据类型, 能识别的类型为:string,number,boolean,function,undefined,object 
13 其中对象,数组,null都判定为object,也就是说typeof不识别Array,typeof arr === Array返回值为flase
14 
15 //2.typeof 判定 构造函数 数据类型  
16 var a = new String(‘123‘);        //typeof a === object
17 var b = new Number(123);          //typeof b === object
18 var c = new Boolean(true);          //typeof c === object
19 var d = new function(){};         //typeof d === object
20 var e = new Object();             //typeof e === object     
21 var f = new Array();             //typeof f === object
22 var g = new Date();                 //typeof g === object
23 结论:typeof 判定构造函数数据类型全部返还object

 

2.instanceof

instanceof运算符可以用来判断某个构造函数的prototype属性是否存在另外一个要检测对象的原型链上。

实例一:普遍用法

A instanceof B :检测B.prototype是否存在于参数A的原型链上.

function Ben() {
}
var ben = new Ben();
console.log(ben instanceof Ben);//true

实例二:继承中判断实例是否属于它的父类

function Ben_parent() {}
function Ben_son() {}
Ben_son.prototype = new Ben_parent();//原型继承
var ben_son = new Ben_son();
console.log(ben_son instanceof Ben_son);//true
console.log(ben_son instanceof Ben_parent);//true

 实例三:复杂用法

function Ben() {}
console.log(Object instanceof Object);     //true
console.log(Function instanceof Function); //true
console.log(Function instanceof Object);   //true
console.log(Ben instanceof Function);      //true
console.log(String instanceof String);   //false
console.log(Boolean instanceof Boolean); //false
console.log(Ben instanceof Ben);         //false

  

 

typeof 和instanceof

标签:存在   bool   null   java   它的   测试   string   运算   ber   

原文地址:http://www.cnblogs.com/ly-blogs/p/6443142.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!