JS中 typeof,instanceof類型檢測方式


在js中的類型檢測目前我所知道的是三種方式,分別有它們的應用場景:

1、typeof:主要用於檢測基本類型.

typeof undefined;//=> undefined
typeof 'a';//=> string
typeof 1;//=> number
typeof true;//=> boolean
typeof {};//=> object
typeof [];//=> object
typeof function() {};//=> function
typeof null;//=> object

2、instanceof:主要用於檢測引用類型(左邊是對象,右邊是函數.根據對象的原形鏈往上找,如果原形鏈上有右邊函數.prototype,返回true;否則返回false)

var obj = {}; obj instanceof Object; //=> true; 
var arr = []; arr instanceof Array; //=> true;
var fn = function() {}; fn instanceof Function; //=> true;

3、Object.prototype.toString.call(sth):由於原形鏈的檢測有漏洞(原型是可以改變的),所以會造成檢測結果不准確,所以可以采用此種形式.

var toString = Object.prototype.toString; toString.call(undefined);//=> [object Undefined]
toString.call(1);//=> [object, Number]
toString.call(NaN);//=> [object, Number]
toString.call('a');//=> [object, String]
toString.call(true);//=> [object, Boolean]
 toString.call({});//=> [object, Object]
toString.call(function() {});//=> [object, Function]
toString.call([]);//=> [object, Array]
toString.call(null);//=> [object, Null]

 

原文地址:https://www.cnblogs.com/littlebirdlbw/p/6860038.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM