代码:
var Symbol = require('./_Symbol');
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Used to resolve the
* [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
* of values.
*/
var nativeObjectToString = objectProto.toString;
/** Built-in value references. */
var symToStringTag = Symbol ? Symbol.toStringTag : undefined;
/**
* A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.
*
* @private
* @param {*} value The value to query.
* @returns {string} Returns the raw `toStringTag`.
*/
function getRawTag(value) {
var isOwn = hasOwnProperty.call(value, symToStringTag),
tag = value[symToStringTag];
try {
value[symToStringTag] = undefined;
var unmasked = true;
} catch (e) {}
var result = nativeObjectToString.call(value);
if (unmasked) {
if (isOwn) {
value[symToStringTag] = tag;
} else {
delete value[symToStringTag];
}
}
return result;
}
module.exports = getRawTag;
疑惑:为什么不直接返回var result = nativeObjectToString.call(value)就行还要那么多操作?
解答:
Symbol.toStringTag可以被用户随意修改,getRawTag是为了获取value最原始的类型,所以先把symToStringTag的值拿出来,再置空,这样就不会影响nativeObjectToString.call(value)。最后再把Symbol.toStringTag属性值还原。
方法缺陷:
不能判断undefined和null类型,nativeObjectToString.call(value)还会报错。