ホームページ  >  記事  >  ウェブフロントエンド  >  JavaScript_javascript スキルにおける Object.prototype.toString メソッドの原理

JavaScript_javascript スキルにおける Object.prototype.toString メソッドの原理

WBOY
WBOYオリジナル
2016-05-16 15:13:581399ブラウズ

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]"

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()

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 a>[[Class]] A string value indicating the type of the object.

それから彼は次のように説明しました。

すべての組み込みオブジェクトの [[Class]] 属性の値は、この仕様によって定義されます。すべてのホスト オブジェクトの [[Class]] 属性の値は、[[Class] であっても) 任意の値にすることができます。組み込みオブジェクト ] 属性によって使用される [[Class]] 属性の値は、ネイティブ オブジェクトがどの組み込み型に属するかを決定するために使用できます。この仕様は、それ以外の方法を提供しないことに注意してください。 Object.prototype.toString メソッドを通じて、プログラムがプロパティの値にアクセスできるようにします (15.2.4.2 を参照)。

言い換えると、Object.prototype.toString メソッドによって返される文字列は、前部の固定「[object」と後部の固定「]」を削除したもので、内部属性 [[class] の値になります。 ]、オブジェクトの型を決定する目的は達成されます。これには、jQuery のツール メソッド $.type() が使用されます。

ES3 では、[[クラス]] の内部プロパティが何種類あるかは仕様書にまとめられていませんが、[[クラス]] の値は合計 10 個あると自分で数えることができます。 ] ネイティブ オブジェクトの内部プロパティはそれぞれ「Array」、「Boolean」、「Date」、「Error」、「Function」、「Math」、「Number」、「Object」、「RegExp」、「String」です。 .

ECMAScript 5

ES5.1 では、仕様がより詳細に記述されることに加えて、Object.prototype.toString メソッドとオブジェクトの [[class]] 内部プロパティの定義にもいくつかの変更があります。 prototype.toString メソッドは次のとおりです:

15.2.4.2 Object.prototype.toString ()

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

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


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


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


クラスを O の内部プロパティ [[Class]] の値とします。


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


ステップ 1 と 2 は ES3 よりも 1、2、3 ステップ増えていることがわかります。ステップ 1 とステップ 2 は、「未定義」と「Null」が ES3 の値に属さないため、非常に特殊です。 [[class]] 属性は、厳密モードとは関係がないことに注意してください (ほとんどの関数では、この値は厳密モードでのみ未定義または null のままになり、非定義モードでは自動的にグローバル オブジェクトになります)。 ES3 エンジンでは、このステップで 3 つのプリミティブ値タイプが対応するパッケージング オブジェクトに変換されますが、ES5 では [[Class. ]] 属性について詳しく説明します:

すべての組み込みオブジェクトの [[Class]] 属性の値は、この仕様によって定義されます。すべてのホスト オブジェクトの [[Class]] 属性の値は、「Arguments」、「Array」、 「Boolean」、「Date」、「Error」、「Function」、「JSON」、「Math」、「Number」、「Object」、「RegExp」、「String」は、内部プロパティを決定するために内部的に使用されるエンジンです。オブジェクトが属する値のタイプ。この仕様では、 Object.prototype.toString メソッドを介する以外に、プログラムがこのプロパティの値にアクセスする他の方法を提供していないことに注意してください (15.2.4.2 を参照)。 >

ES3 と比較すると、最初の違いは、[[class]] の内部属性値が 2 つ増えて 12 種類になったことです。1 つは、引数オブジェクトの [[class]] が「Arguments」になり、以前の値に代わったことです。 「オブジェクト」には、[[クラス]] 値が「JSON」である複数のグローバル オブジェクト JSON が存在します。2 番目の違いは、ホスト オブジェクトの [[クラス]] 内部プロパティの値がこれら 12 つと競合できないことです。ただし、ES3 をサポートするブラウザでは、これらの 10 個の値を意図的に使用しているホスト オブジェクトはないようです。

ECMAScript 6

ES6 はまだ作業中のドラフトにすぎませんが、確かなことは、[[class]] 内部属性がなくなり、別の内部属性 [[NativeBrand]] に置き換えられたことです。 [[NativeBrand]] 属性は次のように定義されています。 :

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

[[NativeBrand]]屬性的解釋:

[[NativeBrand]]內部屬性用來識別某個原生物件是否為符合本規範的某一種特定類型的物件.[[NativeBrand]]內部屬性的值為下面這些枚舉類型的值中的一個:NativeFunction, NativeArray, StringWrapper, BooleanWrapper, NumberWrapper, NativeMath, NativeDate, NativeRegExp, NativeError, NativeJSON, NativeArguments, NativePrivateName.[[NativeBrand]]內部屬性僅用來區分特定類型的ECMAScript10.明確指出的物件類型才有[[NativeBrand]]內部屬性.

表10 — [[NativeBrand]]內部屬性的值

屬性值 對應類型
原生函數 函數物件
NativeArray 數組物件
字串包裝器 字串物件
布爾包裝器 布林物件
數位包裝器 數位物件
NativeMath The Math object
NativeDate Date objects
NativeRegExp RegExp objects
NativeError Error objects
NativeJSON The JSON object
NativeArguments Arguments objects
NativePrivateName Private Name objects

It can be seen that, unlike [[class]], not every object has [[NativeBrand]]. At the same time, the specification of the Object.prototype.toString method has also been changed to the following:

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).

If O has the [[NativeBrand]] internal attribute, let tag be the corresponding value in Table 29.

Otherwise

Let hasTag be the result of calling O’s [[HasProperty]] internal method, with the parameter @@toStringTag.

If hasTag is false, let the tag be "Object".

Otherwise,

Let tag be the result of calling O’s [[Get]] internal method, and the parameter is @@toStringTag.

If tag is an abrupt completion, let tag become NormalCompletion("???").

Let tag be tag.[[value]].

If Type(tag) is not a string, let tag become "???".

If the value of tag is "Arguments", "Array", "Boolean", "Date", "Error", "Function", "JSON", "Math", "Number", "Object", "RegExp ", or

or "String", then let the tag become the result of concatenating the string "~" and the current value of the tag.

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

Table 29 — [[NativeBrand]] Flag Values

[[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]"

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

15.14.5.13 Map.prototype.@@toStringTag

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

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

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

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。