Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

lodash源码分析之isSymbol #52

Open
HeftyKoo opened this issue Dec 12, 2019 · 0 comments
Open

lodash源码分析之isSymbol #52

HeftyKoo opened this issue Dec 12, 2019 · 0 comments
Labels
api 暴露出来的接口 系列文章

Comments

@HeftyKoo
Copy link
Owner

HeftyKoo commented Dec 12, 2019

本文为读 lodash 源码的第五十一篇,后续文章会更新到这个仓库中,欢迎 star:pocket-lodash

gitbook也会同步仓库的更新,gitbook地址:pocket-lodash

依赖

import getTag from './.internal/getTag.js'

《lodash源码分析之数据类型获取的兼容性》

源码分析

isSymbol 用来判断一个值是否为 symbol 类型。

看下源码:

function isSymbol(value) {
  const type = typeof value
  return type == 'symbol' || (type === 'object' && value != null && getTag(value) == '[object Symbol]')
}

第一个条件很好理解,只要用 typeof 判断,返回的值为 symbol 即可。

在看第二个条件之前,先看下这个 lodash 的测试用例:

assert.strictEqual(isSymbol(Object(symbol)), true)

可以看到这里先将一个 symbol 值转换为 object 类型,再传给 isSymbol 时,返回依旧为 true

看下以下代码:

const symbol = Symbol()
typeof Object(symbol) // 'object'
Object.prototype.toString.call(Object(symbol)) // '[object Symbol]'

可以看到,用 typeof 来检测时,返回的是 object, 因此需要第二个条件来判断,即再通过 getTag(value) == '[object Symbol]' 来判断。

相关链接

lodash源码解释:isSymbol

License

署名-非商业性使用-禁止演绎 4.0 国际 (CC BY-NC-ND 4.0)

最后,所有文章都会同步发送到微信公众号上,欢迎关注,欢迎提意见:

作者:对角另一面

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
api 暴露出来的接口 系列文章
Projects
None yet
Development

No branches or pull requests

1 participant