typeof Array, Object, new Class() 都會返回'object', 所以使用typeof不能准確的判斷變量是否為object
typeof []; //object typeof {}; //object typeof new (function (){}); //object typeof 1; //number typeof '1'; //string typeof null; //object typeof true; //boolean
要
准確判斷一個變量是否是一個對象,可以使用constructor以及instanceof判斷。
1. constructor是指該對象的構造函數, 使用constructor時, 要注意, 實例化類時, 類的prototype.constructor需要正確引用。
({}).constructor === Object; //true (1).constructor === Number; //true ([]).constructor === Array; //true ('1').constructor === String; //true (true).constructor === Boolean; //true
2. instanceof是指該對象是否為指定類的實例
({}) instanceof Object; //true ([]) instanceof Array; //true (1) instanceof Number; //true ('1') instanceof String; //true (true) instanceof Boolean; //true