詳解Object.constructor
阿新 • • 發佈:2018-01-17
return 說明 logs nat 常用 func false 實例 判斷
對象的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
詳解Object.constructor