getTag
Do what you love, not what you think you're supposed to do. — Unknown
本文为 《lodash 源码阅读》 系列文章,后续内容会在 github 中发布,欢迎 star,gitbook 同步更新。
源码
原理
通过 Object.prototype.toString
获取 value
的 Symbol.toStringTag
值。 但是许多内置的 JavaScript 对象类型即便没有 toStringTag 属性,也能被 toString() 方法识别并返回特定的类型标签,比如:
这里我们可以看到其中 undefined
跟 null
也能成功获取 tag
,并不需要像源码中那样做 hack,原因是:
从 JavaScript1.8.5 开始 toString()调用 null 返回[object Null],undefined 返回[object Undefined],如第 5 版的 ECMAScript 和随后的 Errata。
参考
Last updated
Was this helpful?