Home > Web Front-end > JS Tutorial > body text

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

WBOY
Release: 2016-05-16 15:13:58
Original
1433 people have browsed it

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方法的原理,希望对大家有所帮助!

source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template