概要
指定したプロトタイプオブジェクトおよびプロパティを持つ、新たなオブジェクトを生成します。
Object オブジェクトのメソッド |
|
---|---|
実装されたバージョン | JavaScript 1.8.5 |
ECMAScript エディション | ECMAScript 5th Edition |
構文
Object.create(proto [, propertiesObject ])
引数
- proto
- 新たに生成されるオブジェクトのプロトタイプになるべきオブジェクトです。
- propertiesObject
- これが指定されかつ未定義である場合、列挙可能な自身のプロパティを持つオブジェクト (つまり、それらのプロパティは自身で定義済みで、またプロトタイプチェインで 列挙可能ではない プロパティです) は新たに生成されるオブジェクトに追加されるプロパティのディスクリプタを、対応するプロパティ名と共に指定します。
説明
引数 proto が null
ではない、またはオブジェクトではない場合、TypeError
例外が発生します。
例
var o; // null をプロトタイプとするオブジェクトを生成します o = Object.create(null); o = {}; // これは以下と同じです: o = Object.create(Object.prototype); // 2 つのサンプルプロパティを持つオブジェクトを生成する例です // (第 2 引数はキーを *プロパティディスクリプタ* に対応づけることに注意してください) o = Object.create(Object.prototype, { // foo は通常の "値を持つプロパティ" です。 foo: { writable:true, configurable:true, value: "hello" }, // bar は getter および setter (アクセサ) プロパティです bar: { configurable: false, get: function() { return 10 }, set: function(value) { console.log("Setting `o.bar` to", value) } }) function Constructor(){} o = new Constructor(); // これは以下と同じです: o = Object.create(Constructor.prototype); // もちろん、実際にコンストラクタ関数の初期化コードがある場合でも、Object.create はそれを反映できません // new がプロトタイプである空のオブジェクトを作成し、 // 値が 42 であるプロパティ 'p' 1 つを追加します。 o = Object.create({}, { p: { value: 42 } }) // 既定でプロパティは書き換え (writable)、列挙 (enumerable)、変更 (configurable) が不可になります: o.p = 24 o.p //42 o.q = 12 for (var prop in o) { console.log(prop) } //"q" delete o.p //false // ES3 プロパティの定義 o2 = Object.create({}, { p: { value: 42, writable: true, enumerable: true, configurable: true } });
ブラウザの互換性
Kangax's compat table に基づきます。
機能 | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
---|---|---|---|---|---|
基本サポート | 5 | 4.0 (2) | 9 | 11.60 | 5 |
機能 | Firefox Mobile (Gecko) | Android | IE Mobile | Opera Mobile | Safari Mobile |
---|---|---|---|---|---|
基本サポート | 4.0 (2) | (有) | ? | 11.50 | (有) |
Polyfill
if (!Object.create) { Object.create = function (o) { if (arguments.length > 1) { throw new Error('Object.create implementation only accepts the first parameter.'); } function F() {} F.prototype = o; return new F(); }; }
このポリフィルは、プロトタイプは選択されたが第 2 引数を考慮しない状況向けに、新規オブジェクトを生成する主要な利用法に対応します。
関連情報
Object.defineProperty
Object.defineProperties
Object.prototype.isPrototypeOf
getPrototypeOf
に関する John Resig 氏の投稿