前言
记录那些实用的知识点。
数据类型
- js数据类型:
undefined
、null
、布尔值(Boolean
)、字符串(String
)、数值(Number
)、对象(Object
)、Symbol
(ES6,函数生成); typeof
:返回number
、boolean
、symbol
、string
、object
、undefined
、function
,typeof null===object
,typeof []===object
;Object.prototype.toString
(最精确):返回[object xxx],其中xxx为数据类型;
Object.prototype.toString.call('') ; // [object String]
Object.prototype.toString.call(1) ; // [object Number]
Object.prototype.toString.call(true) ; // [object Boolean]
Object.prototype.toString.call(Symbol()); //[object Symbol]
Object.prototype.toString.call(undefined) ; // [object Undefined]
Object.prototype.toString.call(null) ; // [object Null]
Object.prototype.toString.call(new Function()) ; // [object Function]
Object.prototype.toString.call(new Date()) ; // [object Date]
Object.prototype.toString.call([]) ; // [object Array]
Object.prototype.toString.call(new RegExp()) ; // [object RegExp]
Object.prototype.toString.call(new Error()) ; // [object Error]
Object.prototype.toString.call(document) ; // [object HTMLDocument]
Object.prototype.toString.call(window) ; //[object global] window 是全局对象 global 的引用
constructor
:prototype的一个属性,当函数被定义时候,js引擎会为函数添加原型prototype,并且这个prototype中constructor属性指向函数引用, 因此重写prototype会丢失原来的constructor。此方法判断不了null 和 undefined(没有constructor)。如果自定义对象,开发者重写prototype之后,原有的constructor会丢失,因此,为了规范开发,在重写对象原型时一般都需要重新给 constructor 赋值,以保证对象实例的类型不被篡改。
instanceof
:判断 A 是否为 B 的实例。[]的原型指向Array.prototype,间接指向Object.prototype, 因此[] instanceof Array
返回true
,[] instanceof Object
也返回true
。instanceof
只能用来判断两个对象是否属于实例关系, 而不能判断一个对象实例具体属于哪种类型。- 实现一个类型判断的高阶函数:
function isType(type){
return function(obj){
return Object.prototype.toString.call(obj)===`[object ${type}]`;
}
}
const isArray=isType('Array');
const isString=isType('String');
console.log(isArray([1,2,[3,4]]);//true
console.log(isString({}); //false