對象的constructor屬性引用了該對象的構造函數.對於 Object 對象,該指針指向原始的 Object() 函數.以下:函數
var obj = {}; obj.constructor //ƒ Object() { [native code] } obj.constructor == Object //true var arr = []; arr.constructor //ƒ Array() { [native code] } arr.constructor == Array //true function Fun(){ console.log('function'); } var fun = new Fun(); //實例化 fun.constructor //ƒ Fun(){console.log('function')} 【打印出來的引用是Fun函數,說明fun的引用是Fun函數】 Fun.constructor //ƒ Function() { [native code] } 【打印出來的引用是Funcion函數,說明Fun的引用是Function函數】 fun.constructor == Fun //true 【再次證實fun的constructor屬性引用了fun對象的構造函數】 fun.constructor == Fun.constructor //false
constructor經常使用於判斷未知對象的類型,以下:指針
function isArray (val){ var isTrue = typeof val == 'object' && val.constructor == Array; return isTrue?true:false; } var arr = isArray([1,2,3,4,5]); console.log(arr); //true