# 获取数据类型兼容性
const dataViewTag = '[object DataView]';
const mapTag = '[object Map]';
const objectTag = '[object Object]';
const promiseTag = '[object Promise]';
const setTag = '[object Set]';
const weakMapTag = '[object WeakMap]';
/** Used to detect maps, sets, and weakmaps. */
const dataViewCtorString = `${DataView}`;
const mapCtorString = `${Map}`;
const promiseCtorString = `${Promise}`;
const setCtorString = `${Set}`;
const weakMapCtorString = `${WeakMap}`;
let getTag = baseGetTag;
// Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6.
if (
(DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag)
|| (getTag(new Map) != mapTag)
|| (getTag(Promise.resolve()) != promiseTag)
|| (getTag(new Set) != setTag)
|| (getTag(new WeakMap) != weakMapTag)) {
// 扩展baseGetTag函数
getTag = (value) => {
const result = baseGetTag(value);
const Ctor = result == objectTag ? value.constructor : undefined;
const ctorString = Ctor ? `${Ctor}` : '';
if (ctorString) {
switch (ctorString) {
case dataViewCtorString: return dataViewTag;
case mapCtorString: return mapTag;
case promiseCtorString: return promiseTag;
case setCtorString: return setTag;
case weakMapCtorString: return weakMapTag;
}
}
return result;
}
}
首先获取了全局构造函数,根据这些构造函数字符来判断当前浏览器是否能够识别ES6新的数据类型。
如果不识别,则获取实例的构造函数,通过toSring和全局构造函数字符对比,从而兼容的获取了数据类型。
Promise.resolve
,Promise需要调用resolve才能获取到Promise
对象,否则为函数类型。