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

Object.prototype.toString.call() #1

Open
lizhongzhen11 opened this issue Jun 19, 2018 · 0 comments
Open

Object.prototype.toString.call() #1

lizhongzhen11 opened this issue Jun 19, 2018 · 0 comments
Labels
js基础 Good for newcomers

Comments

@lizhongzhen11
Copy link
Owner

记得之前在某篇讲解vue源码的文章里第一次看到这个方法,心里便留意了起来,后来日常开发需要去判断类型时百试不爽,但一直不明所以,直到今天在看了如何继承Date对象?由一道题彻底弄懂JS继承。这篇博客,我才大致了解到原来该方法访问的是对象的[[Class]]属性。

[[Class]]与Internal slot

  • 在ES5中,每种内置对象都定义了 [[Class]] 内部属性的值,[[Class]] 内部属性的值用于内部区分对象的种类
    • Object.prototype.toString访问的就是这个[[Class]]
    • 规范中除了通过Object.prototype.toString,没有提供任何手段使程序访问此值。
    • 而且Object.prototype.toString输出无法被修改
  • 而在ES6中,之前的 [[Class]] 不再使用,取而代之的是一系列的internal slot
    • Internal slot 对应于与对象相关联并由各种ECMAScript规范算法使用的内部状态,它们没有对象属性,也不能被继承
    • 根据具体的 Internal slot 规范,这种状态可以由任何ECMAScript语言类型或特定ECMAScript规范类型值的值组成
    • 通过Object.prototype.toString,仍然可以输出Internal slot
    • 简单点理解(简化理解),Object.prototype.toString的流程是:如果是基本数据类型(除去Object以外的几大类型),则返回原本的slot, 如果是Object类型(包括内置对象以及自己写的对象),则调用Symbol.toStringTag
    • Symbol.toStringTag方法的默认实现就是返回对象的Internal slot,这个方法可以被重写

ES6新增的一些,这里未提到:(如Promise对象可以输出[object Promise]

@lizhongzhen11 lizhongzhen11 added the js基础 Good for newcomers label Sep 14, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
js基础 Good for newcomers
Projects
None yet
Development

No branches or pull requests

1 participant