Object.prototype.toString()【文字列変換】メソッド
メモ
- 文字列に変換
- 書き換え可能 (prototype.toString を書き換え・[@@toStringTag]プロパティ の定義)
- 標準組み込みオブジェクトの判別に利用可能
- 詳細は、Object【オブジェクト】オブジェクトのメモ参照
構文
- toString ()
- なし
変換文字列
値 | 戻り値 | 備考 |
---|---|---|
undefined | "[object Undefined]" | |
null | "[object Null]" | |
標準組み込みオブジェクト | "[object Arguments]" | String型等も全てオブジェクト |
"[object Array]" | ||
"[object Boolean]" | ||
"[object Date]" | ||
"[object Error]" | ||
"[object Function]" | ||
"[object Number]" | ||
"[object Object]" | ||
"[object RegExp]" | ||
"[object String]" | ||
[ @@toStringTag ] 【タグ】プロパティ を持つオブジェクト | "[object %TypedArray%]" | "[object オブジェクト名]" |
"[object ArrayBuffer]" | ||
"[object DataView]" | ||
"[object GeneratorFunction]" | ||
"[object Generator]" | ||
"[object JSON]" | ||
"[object Map]" | ||
"[object Math]" | ||
"[object Promise]" | ||
"[object Set]" | ||
"[object Symbol]" | ||
"[object WeakMap]" | ||
"[object WeakSet]" | ||
[ @@toStringTag ] 【タグ】プロパティ を定義 | "[object 【プロパティ定義】]" | 実装:[ Symbol.toStringTag ] |
その他 | "[object Object]" |
例
var toString = Object.prototype.toString;
console.log(toString.call(undefined)); // 出力:[object Undefined]
console.log(toString.call(null)); // 出力:[object Null]
console.log(toString.call(new String())); // 出力:[object String]
console.log(toString.call(new Number())); // 出力:[object Number]
console.log(toString.call(Math)); // 出力:[object Math]
var obj = { a:1, b:2, c:3 };
console.log(obj.toString()); // 出力:[object Object]
obj[Symbol.toStringTag] = "MyObject"; // [@@toStringTag]
console.log(obj.toString()); // 出力:[object MyObject]
function Point(x, y) {
this.x = x;
this.y = y;
}
obj = new Point(2, 3);
console.log(obj.toString()); // 出力:[object Object]
// toString() 書き換え
Point.prototype.toString = function pointToString() {
var ret = '[ x = ' + this.x + ', y = ' + this.y + ' ]';
return ret;
}
console.log(obj.toString()); // 出力:[ x = 2, y = 3 ]