Object.prototype.toString.call(obj) 为何有用以及疑惑点

能检测的方法不少 基本上的疑惑点是如何检测object null array function,能准确的检测出来这几个的都是好方法数组

typeof 0;  //number;
typeof true;  //boolean;
typeof undefined;  //undefined;
typeof "hello world"   //string;
typeof function(){};   //function;

typeof null; //object
typeof {};  //object;
typeof []; //object

 

1. typeof 为何不许spa

  由于当他在检测null array object的时候  都是object,这是由于这几个都是Object重写的实例  这个也会帮助咱们理解标题的疑惑prototype

2.Object.prototype.toString.call(obj) 为何有用code

  toString方法返回反映这个对象的字符串对象

  为何它就能准确判断类型呢,为何用Object.tostring 方法就不行呢blog

  仍是那一句话 null array object都是Object重写的实例 他们是有本身的tostring的方法 按照原型链的思路,会优先使用重写后的tostring方法,而咱们只想用原型链上的tostring的方法原型链

  验证字符串

var arr=[1,2,3];
console.log(Array.prototype.hasOwnProperty("toString"));//true
console.log(arr.toString());//1,2,3
delete Array.prototype.toString;//delete操做符能够删除实例属性
console.log(Array.prototype.hasOwnProperty("toString"));//false
console.log(arr.toString());//"[object Array]"

  当咱们删除了array本身的tostring方法后 再次访问会调用原型链后的方法 跟Object.prototype.tostring(obj)同样了原型

 

扩展:其余能检测类型的方法string

  1. instanceof 

  能够检测是不是该原型的实例

// 判断 foo 是不是 Foo 类的实例
function Foo(){} 
var foo = new Foo(); 
console.log(foo instanceof Foo)//true

 缺点:1.由于数组属于object中的一种,因此数组instanceof object,也是true.

var a={};
a instanceof Object  //true
a intanceof Array     //false
var b=[];
b instanceof Array  //true
b instanceof  Object //true

  缺点:2.instanceof不能区分基本类型string和boolean,除非是字符串对象和布尔对象

var c='abc';
c instanceof String; //false
var d=new String();
d instanceof String  //true

  2.constructor 

  除了undefined和null,其余类型的变量均能使用constructor判断出类型.

  缺点:这个方法容易被改写

相关文章
相关标签/搜索