Home Web Front-end JS Tutorial The principle of Object.prototype.toString method in JavaScript_javascript skills

The principle of Object.prototype.toString method in JavaScript_javascript skills

May 16, 2016 pm 03:13 PM

In JavaScript, the most reliable way to determine which built-in type an object value belongs to is through the Object.prototype.toString method.

var arr = [];
console.log(Object.prototype.toString.call(arr)) //"[object Array]"
Copy after login

What this article is going to talk about is how the toString method does this and what the principle is.

ECMAScript 3

In ES3, the specification of the Object.prototype.toString method is as follows:

15.2.4.2 Object.prototype.toString()
Copy after login

When the toString method is called, the following steps will be performed:

1. Get the value of the [[Class]] attribute of this object.

2. Calculate the three strings "[object", the operation result Result(1) of the first step, and the new string after "]" concatenation.

3. Return the operation result of the second step Result(2).

[[Class]] is an internal property that all objects (native objects and host objects) have. In the specification, [[Class]] is defined like this

内部属性 描述
[[Class]] 一个字符串值,表明了该对象的类型.
<🎜>Internal properties<🎜> <🎜>Description<🎜> <🎜> <🎜> <🎜> [[Class]] A string value indicating the type of the object. <🎜>

Then he gave an explanation:

The value of the [[Class]] attribute of all built-in objects is defined by this specification. The value of the [[Class]] attribute of all host objects can be any value, even the [[Class] used by the built-in object ] attribute. The value of the [[Class]] attribute can be used to determine which built-in type a native object belongs to. It should be noted that this specification does not provide any other way except through the Object.prototype.toString method. Let the program access the value of the property (see 15.2.4.2).

In other words, the string returned by the Object.prototype.toString method, remove the fixed "[object" in the front and the fixed "]" in the back, is the value of the internal attribute [[class]], which is achieved The purpose of determining the object type. The tool method $.type() in jQuery is used for this.

In ES3, the specification document does not summarize how many types of [[class]] internal properties there are, but we can count by ourselves. There are a total of 10 values ​​​​of the [[class]] internal properties of native objects. respectively. Is: "Array", "Boolean", "Date", "Error", "Function", "Math", "Number", "Object", "RegExp", "String".

ECMAScript 5

In ES5.1, in addition to the specification being written in more detail, there are also some changes in the definition of the Object.prototype.toString method and [[class]] internal properties. The specification of the Object.prototype.toString method is as follows:

15.2.4.2 Object.prototype.toString ( )

When the toString method is called, the following steps will be performed:

If the value of this is undefined, return "[object Undefined]".

If the value of this is null, return "[object Null]".

Let O be the result of calling ToObject(this).

Let class be the value of O’s internal property [[Class]].

Returns the new string after concatenating the three strings "[object ", class, and "]".

It can be seen that there are 1, 2, and 3 more steps than ES3. Steps 1 and 2 are new rules and are quite special, because "Undefined" and "Null" do not belong to the values ​​of the [[class]] attribute. It should be noted that this has nothing to do with strict mode (for most functions, the value of this will remain undefined or null only in strict mode, and will automatically become a global object in non-strict mode). Step 3 is not a new rule, because In the ES3 engine, the three primitive value types will be converted into corresponding packaging objects in this step, but it is not written in the specification. In ES5, the [[Class]] attribute is explained in more detail:

The value of the [[Class]] attribute of all built-in objects is defined by this specification. The value of the [[Class]] attribute of all host objects can be except "Arguments", "Array", "Boolean", "Date ", "Error", "Function", "JSON", "Math", "Number", "Object", "RegExp", "String". The internal property is the engine Internally used to determine which type of value an object belongs to. It should be noted that this specification does not provide any other way for the program to access the value of this property except through the Object.prototype.toString method (see 15.2.4.2 ).

Compared with ES3, the first difference is that [[class]] has two more internal attribute values, becoming 12 types. One is that [[class]] of the arguments object becomes "Arguments", and Instead of the previous "Object", there are multiple global objects JSON, whose [[class]] value is "JSON". The second difference is that the value of the [[class]] internal property of the host object cannot be It conflicts with these 12 values, but in browsers that support ES3, it seems that no host objects are deliberately using those 10 values.

ECMAScript 6

ES6 is still only a working draft, but what is certain is that the [[class]] internal attribute is gone and replaced by another internal attribute [[NativeBrand]]. The [[NativeBrand]] attribute is defined like this:

内部属性 属性值 描述
[[NativeBrand]] 枚举NativeBrand的一个成员. 该属性的值对应一个标志值(tag value),可以用来区分原生对象的类型.

[[NativeBrand]] 属性の説明:

[[NativeBrand]] 内部プロパティは、ネイティブ オブジェクトがこの仕様に準拠する特定の種類のオブジェクトであるかどうかを識別するために使用されます。 [[NativeBrand]] 内部プロパティの値は、次の列挙型 A: NativeFunction、NativeArray、StringWrapper、BooleanWrapper、NumberWrapper、NativeMath、NativeDate、NativeRegExp、NativeError、NativeJSON、NativeArguments、NativePrivateName の内部プロパティは、ECMAScript ネイティブ オブジェクトの特定の種類を区別するためにのみ使用されます。表 10 明示的に指定されたオブジェクト タイプのみが [[NativeBrand]] 内部プロパティを持ちます。

表 10 — [[NativeBrand]] 内部プロパティの値

属性值 对应类型
NativeFunction Function objects
NativeArray Array objects
StringWrapper String objects
BooleanWrapper Boolean objects
NumberWrapper Number objects
ネイティブ数学 Math オブジェクト
ネイティブ日付 日付オブジェクト
NativeRegExp RegExp オブジェクト
ネイティブエラー エラーオブジェクト
ネイティブ JSON JSON オブジェクト
NativeArguments 引数オブジェクト
ネイティブプライベート名 プライベート名オブジェクト

[[class]] とは異なり、すべてのオブジェクトが [[NativeBrand]] を持っているわけではないことがわかります。同時に、Object.prototype.toString メソッドの仕様も次のように変更されています。 🎜>

15.2.4.2 Object.prototype.toString ()

toString メソッドが呼び出されると、次の手順が実行されます。

この値が未定義の場合は、「[オブジェクト未定義]」を返します。


this の値が null の場合、「[object Null]」を返します。


ToObject(this) を呼び出した結果を O とします。


O が [[NativeBrand]] 内部属性を持つ場合、tag を表 29 の対応する値にします。


そうでない場合


hasTag を、パラメータ @@toStringTag を使用して O の [[HasProperty]] 内部メソッドを呼び出した結果とします。


hasTag が false の場合、タグは「Object」になります。


それ以外の場合、


タグを O の [[Get]] 内部メソッドを呼び出した結果とし、パラメータは @@toStringTag とします。


タグが突然完了の場合、タグを NormalCompletion("???") にします。


タグを tag.[[value]] にします。


Type(tag)が文字列でない場合、タグは「???」になります。


タグの値が「Arguments」、「Array」、「Boolean」、「Date」、「Error」、「Function」、「JSON」、「Math」、「Number」、「Object」、「」の場合RegExp "、または

または "String" の場合、タグは文字列 "~" とタグの現在の値を連結した結果になります。


3 つの文字列「[object」、tag、および「]」を連結した後の新しい文字列を返します。

表 29 — [[NativeBrand]] フラグの値

[[NativeBrand]] value Flag value
NativeFunction <font face="NSimsun">"Function"</font>
NativeArray <font face="NSimsun">"Array"</font>
StringWrapper <font face="NSimsun">"String"</font>
BooleanWrapper <font face="NSimsun">"Boolean"</font>
NumberWrapper <font face="NSimsun">"Number"</font>
NativeMath <font face="NSimsun">"Math"</font>
NativeDate <font face="NSimsun">"Date"</font>
NativeRegExp <font face="NSimsun">"RegExp"</font>
NativeError <font face="NSimsun">"Error"</font>
NativeJSON <font face="NSimsun">"JSON"</font>
NativeArguments <font face="NSimsun">"Arguments"</font>

可以看到,在规范上有了很大的变化,不过对于普通用户来说,貌似感觉不到.

也许你发现了,ES6里的新类型Map,Set等,都没有在表29中.它们在执行toString方法的时候返回的是什么?

console.log(Object.prototype.toString.call(Map())) //"[object Map]"
console.log(Object.prototype.toString.call(Set())) //"[object Set]"
Copy after login

其中的字符串"Map"是怎么来的呢:

15.14.5.13 Map.prototype.@@toStringTag

@@toStringTag 属性的初始值为字符串"Map".

由于ES6的规范还在制定中,各种相关规定都有可能改变,所以如果想了解更多细节.看看下面这两个链接,现在只需要知道的是:[[class]]没了,使用了更复杂的机制.

以上所述是小编给大家分享的JavaScript中Object.prototype.toString方法的原理,希望对大家有所帮助!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How do I create and publish my own JavaScript libraries? How do I create and publish my own JavaScript libraries? Mar 18, 2025 pm 03:12 PM

Article discusses creating, publishing, and maintaining JavaScript libraries, focusing on planning, development, testing, documentation, and promotion strategies.

How do I optimize JavaScript code for performance in the browser? How do I optimize JavaScript code for performance in the browser? Mar 18, 2025 pm 03:14 PM

The article discusses strategies for optimizing JavaScript performance in browsers, focusing on reducing execution time and minimizing impact on page load speed.

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

How do I debug JavaScript code effectively using browser developer tools? How do I debug JavaScript code effectively using browser developer tools? Mar 18, 2025 pm 03:16 PM

The article discusses effective JavaScript debugging using browser developer tools, focusing on setting breakpoints, using the console, and analyzing performance.

How do I use source maps to debug minified JavaScript code? How do I use source maps to debug minified JavaScript code? Mar 18, 2025 pm 03:17 PM

The article explains how to use source maps to debug minified JavaScript by mapping it back to the original code. It discusses enabling source maps, setting breakpoints, and using tools like Chrome DevTools and Webpack.

How do I use Java's collections framework effectively? How do I use Java's collections framework effectively? Mar 13, 2025 pm 12:28 PM

This article explores effective use of Java's Collections Framework. It emphasizes choosing appropriate collections (List, Set, Map, Queue) based on data structure, performance needs, and thread safety. Optimizing collection usage through efficient

TypeScript for Beginners, Part 2: Basic Data Types TypeScript for Beginners, Part 2: Basic Data Types Mar 19, 2025 am 09:10 AM

Once you have mastered the entry-level TypeScript tutorial, you should be able to write your own code in an IDE that supports TypeScript and compile it into JavaScript. This tutorial will dive into various data types in TypeScript. JavaScript has seven data types: Null, Undefined, Boolean, Number, String, Symbol (introduced by ES6) and Object. TypeScript defines more types on this basis, and this tutorial will cover all of them in detail. Null data type Like JavaScript, null in TypeScript

Getting Started With Chart.js: Pie, Doughnut, and Bubble Charts Getting Started With Chart.js: Pie, Doughnut, and Bubble Charts Mar 15, 2025 am 09:19 AM

This tutorial will explain how to create pie, ring, and bubble charts using Chart.js. Previously, we have learned four chart types of Chart.js: line chart and bar chart (tutorial 2), as well as radar chart and polar region chart (tutorial 3). Create pie and ring charts Pie charts and ring charts are ideal for showing the proportions of a whole that is divided into different parts. For example, a pie chart can be used to show the percentage of male lions, female lions and young lions in a safari, or the percentage of votes that different candidates receive in the election. Pie charts are only suitable for comparing single parameters or datasets. It should be noted that the pie chart cannot draw entities with zero value because the angle of the fan in the pie chart depends on the numerical size of the data point. This means any entity with zero proportion

See all articles