首頁  >  文章  >  web前端  >  JavaScript中Object.prototype.toString方法的原理_javascript技巧

JavaScript中Object.prototype.toString方法的原理_javascript技巧

WBOY
WBOY原創
2016-05-16 15:13:581399瀏覽

在JavaScript中,想要判斷某個物件值屬於哪種內建型別,最可靠的做法就是透過Object.prototype.toString方法.

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

本文要講的就是,toString方法是如何做到這一點的,原理是什麼.

ECMAScript 3

在ES3中,Object.prototype.toString方法的規格如下:

15.2.4.2 Object.prototype.toString()

在toString方法被呼叫時,會執行下面的操作步驟:

1. 取得this物件的[[Class]]屬性的值.

2. 計算出三個字串"[object ", 第一步的操作結果Result(1), 以及 "]"連接後的新字串.

3. 傳回第二步驟的操作結果Result(2).

[[Class]]是一個內部屬性,所有的物件(原生物件和宿主物件)都擁有該屬性.在規範中,[[Class]]是這麼定義的

内部属性 描述
[[Class]] 一个字符串值,表明了该对象的类型.
內部屬性 描述 a>[[Class]] 一個字串值,表示了該物件的類型.

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

すべての組み込みオブジェクトの [[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]] attribute explanation:

[[NativeBrand]] internal properties are used to identify whether a native object is a specific type of object that complies with this specification. The value of the [[NativeBrand]] internal property is one of the values ​​of the following enumeration types A: NativeFunction, NativeArray, StringWrapper, BooleanWrapper, NumberWrapper, NativeMath, NativeDate, NativeRegExp, NativeError, NativeJSON, NativeArguments, NativePrivateName. [[NativeBrand]] internal properties are only used to distinguish specific types of ECMAScript native objects. Only in Table 10 Only explicitly specified object types have [[NativeBrand]] internal properties.

Table 10 — Values ​​of [[NativeBrand]] internal properties

属性值 对应类型
NativeFunction Function objects
NativeArray Array objects
StringWrapper String objects
BooleanWrapper Boolean objects
NumberWrapper Number objects
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