lodash analysis
  • Introduction
  • Tips
    • 高阶函数
    • 从 ECMAScript 中理解 Symbol 类型转换
  • Array
    • findLastIndex
    • map
  • Collection
    • countBy
    • findLast
    • flatMap
    • partition
    • reduce
  • Function
    • after
    • before
    • debounce
    • defer
    • delay
    • flip
    • memoize
    • negate
    • once
    • overArgs
    • throttle
  • Lang
    • isArguments
    • isArrayLike
    • isBuffer
    • isLength
    • isObject
    • isObjectLike
    • isSymbol
    • isTypedArray
    • isUndefined
    • toFinite
    • toNumber
  • Math
    • add
    • ceil
    • divide
    • floor
    • maxBy
    • mean
    • meanBy
    • minBy
    • multiply
    • round
    • subtract
    • sum
    • sumBy
  • Number
    • clamp
    • inRange
    • random
  • Object
    • keys
  • .internal
    • arrayLikeKeys
    • arrayReduce
    • baseAssignValue
    • baseEach
    • baseFindIndex
    • baseFlatten
    • baseFor
    • baseForOwn
    • baseInRange
    • baseReduce
    • baseSum
    • baseToNumber
    • baseToString
    • createMathOperation
    • createRound
    • getTag
    • isFlattenable
    • isIndex
    • nodeTypes
  • Date
    • now(已弃用)
Powered by GitBook
On this page
  1. .internal

getTag

PreviouscreateRoundNextisFlattenable

Last updated 6 years ago

Was this helpful?

CtrlK
  • 源码
  • 原理
  • 参考

Was this helpful?

Do what you love, not what you think you're supposed to do. — Unknown

本文为 《lodash 源码阅读》 系列文章,后续内容会在 github 中发布,欢迎 star,gitbook 同步更新。

源码

const toString = Object.prototype.toString;

/**
 * 获取 value 的 Symbol.toStringTag
 *
 * @private
 * @param {*} value 需要查询的参数
 * @returns {string} 返回对应的 toStringTag
 */
function getTag(value) {
  if (value == null) {
    return value === undefined ? '[object Undefined]' : '[object Null]';
  }
  return toString.call(value);
}

原理

通过 Object.prototype.toString 获取 value 的 Symbol.toStringTag值。 但是许多内置的 JavaScript 对象类型即便没有 toStringTag 属性,也能被 toString() 方法识别并返回特定的类型标签,比如:

Object.prototype.toString.call('foo'); // "[object String]"
Object.prototype.toString.call([1, 2]); // "[object Array]"
Object.prototype.toString.call(3); // "[object Number]"
Object.prototype.toString.call(true); // "[object Boolean]"
Object.prototype.toString.call(undefined); // "[object Undefined]"
Object.prototype.toString.call(null); // "[object Null]"
// ... and more

这里我们可以看到其中 undefined 跟 null 也能成功获取 tag,并不需要像源码中那样做 hack,原因是:

从 JavaScript1.8.5 开始 toString()调用 null 返回[object Null],undefined 返回[object Undefined],如第 5 版的 ECMAScript 和随后的 Errata。

参考

  • MDN - Symbol.toStringTag

  • MDN - Object.prototype.toString()