包装类型、类型检测

包装类型

var str="string";
var strObj=new String("string");
/*
访问基本类型的属性会先尝试转换为包装类型,但之后这个包装对象会被抛弃。
所以可以访问基本类型的成员,但不能够设置
*/
str.length;//6
str.t=1;
str.t;//undefined

 

类型检测

常见方法:typeof、instanceof、Object.prototype.toString、constructor、duck type(特征)

typeof 方便判断基本类型和函数类型

typeof 100;//"number"
typeof true;//"boolean"
typeof function(){};//"function"
typeof undefined;//"undefined"
typeof {};//"object"
typeof NaN;//"number" Infinity同理
typeof null;//"object" 小心这个坑

 

instanceof 判断对象类型(使用原型链实现)

期望左侧是一个对象,如果说基本类型,返回fasle

期望右侧是一个函数对象/函数构造器,否则抛出TypeError 异常

之后判断左侧的prototype链上是否有右侧的prototype属性

$("body") instanceof $;//true jquery
function Person(){
};

function Student(){
};

Student.prototype=new Person();
Student.prototype.constructor=Student;

new Student() instanceof Person;//true

不同的window或iframe不能使用instanceof 

 

Object.prototype.toString防止子类重写以及空指针

 

Object.prototype.toString.apply([]);//"[object Array]" 

Object.prototype.toString.apply(undefined); === “[object Undefined]”

Object.prototype.toString.apply(null); === “[object Null]”
//IE6/7/8 Object.prototype.toString.apply(null) 返回”[object Object]”

 

posted on 2015-11-03 19:55  cbwleft  阅读(115)  评论(0)    收藏  举报