From 33058f2b292b3a581333bdfb21b8f671898c5060 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:40:17 -0500 Subject: initial commit --- .../global_objects/object/tosource/index.html | 131 +++++++++++++++++++++ 1 file changed, 131 insertions(+) create mode 100644 files/ja/web/javascript/reference/global_objects/object/tosource/index.html (limited to 'files/ja/web/javascript/reference/global_objects/object/tosource/index.html') diff --git a/files/ja/web/javascript/reference/global_objects/object/tosource/index.html b/files/ja/web/javascript/reference/global_objects/object/tosource/index.html new file mode 100644 index 0000000000..691ea3adda --- /dev/null +++ b/files/ja/web/javascript/reference/global_objects/object/tosource/index.html @@ -0,0 +1,131 @@ +--- +title: Object.prototype.toSource() +slug: Web/JavaScript/Reference/Global_Objects/Object/toSource +tags: + - JavaScript + - Method + - Non-standard + - Object + - Obsolete + - Prototype +translation_of: Web/JavaScript/Reference/Global_Objects/Object/toSource +--- +
{{JSRef}} {{obsolete_header}}
+ +

toSource() メソッドは、オブジェクトのソースコードを表す文字列を返します。

+ +

構文

+ +
Object.toSource();
+obj.toSource();
+ +

返値

+ +

オブジェクトのソースコードを表す文字列です。

+ +

解説

+ +

toSource() メソッドは以下の値を返します。

+ + + +

デバッグ時に toSource() を呼び出して、オブジェクトの内容を調べることができます。

+ +

toSource() メソッドのオーバーライド

+ +

オブジェクトが toSource() メソッドをオーバーライドしても安全です。例えば次のコードを見てください。

+ +
function Person(name) {
+  this.name = name;
+}
+
+Person.prototype.toSource = function Person_toSource() {
+  return 'new Person(' + uneval(this.name) + ')';
+};
+
+console.log(new Person('Joe').toSource()); // ---> new Person("Joe")
+
+ +

組み込み toSource() メソッド

+ +

コア JavaScript のそれぞれの型は独自の toSource() メソッドを持っています。これらのオブジェクトの例を示します。

+ + + +

循環オブジェクトの正弦

+ +

再帰的にリンクされたリストや双方向に移動可能なツリーなど、自分自身への参照を含むオブジェクトの場合、 toSource() は Firefox 24 のように自己参照を再生成しません。例えば、次のようになります。

+ +
var obj1 = {};
+var obj2 = { a: obj1 };
+obj1.b = obj2;
+
+console.log('Cyclical: ' + (obj1.b.a == obj1));
+
+var objSource = obj1.toSource(); // returns "({b:{a:{}}})"
+
+obj1 = eval(objSource);
+
+console.log('Cyclical: ' + (obj1.b.a == obj1));
+
+ +

循環構造が採用されていて toSource() が必要な場合、オブジェクトはコンストラクターへの参照を使用するか、無名関数を提供するかのいずれかの方法で、 toSource() へのオーバーライドを提供しなければなりません。

+ +

+ +

toSource() の使用

+ +

次のコードは Dog オブジェクト型を定義して theDog、すなわち Dog 型のオブジェクトを生成します。

+ +
function Dog(name, breed, color, sex) {
+  this.name = name;
+  this.breed = breed;
+  this.color = color;
+  this.sex = sex;
+}
+
+theDog = new Dog('Gabby', 'Lab', 'chocolate', 'female');
+
+ +

toSource() メソッドを theDog に対して呼び出すと、そのオブジェクトを定義する JavaScript のソースが表示されます。

+ +
theDog.toSource();
+// returns ({name:"Gabby", breed:"Lab", color:"chocolate", sex:"female"})
+
+ +

仕様書

+ +

標準の一部ではありません。 JavaScript 1.3 で実装されました。

+ +

ブラウザーの互換性

+ +
+ + +

{{Compat("javascript.builtins.Object.toSource")}}

+
+ +

関連情報

+ + -- cgit v1.2.3-54-g00ecf