Object.create()
Object.create()はオブジェクトの継承を行うためのメソッドです。
ECMAScript5で追加されたメソッドでIE9から利用できます。
以下のようにして継承元のオブジェクトを引数に指定することで機能が継承された新しいオブジェクトを作成できます。
obj1 = {
text1 : "text1",
text2 : "text2"
}
obj2 = Object.create(obj1);
console.log(obj2.text1);//text1
以下のサンプルではobj1の機能を継承したobj2を作成しています。作成したobj2の値を変更した場合は元のオブジェクトであるobj1に影響はありません。
obj1 = {
text1 : "text1",
text2 : "text2"
}
obj2 = Object.create(obj1)
obj2.text1 = "text1!!";
console.log(obj1.text1);//text1
console.log(obj2.text1);//text1!!
しかし、継承元のobj1への変更はobj2に影響されます。
obj1 = {
text1 : "text1",
text2 : "text2"
}
obj2 = Object.create(obj1)
obj1.text1 = "text1!!";
console.log(obj1.text1);//text1!!
console.log(obj2.text1);//text1!!
protptype継承などで利用することでスーパークラスに影響を与えないサブクラスが作成できます。
//スーパークラスの作成
var Bar = function(){}
Bar.prototype.foo = function(){
console.log("text1");
}
//サブクラスの作成
var Bar2 = function(){}
Bar2.prototype = Object.create(Bar.prototype);
Bar2.prototype.constructor = Bar;
//サブクラスのメソッドをオーバーライド
Bar2.prototype.foo = function(){
console.log("text2");
}
var bar = new Bar();
bar.foo();//test1
var bar2 = new Bar2();
bar2.foo();//test2
第2引数で継承時に新しいプロパティを指定することができます。
obj1 = {
text1 : "text1",
text2 : "text2"
}
obj2 = Object.create(obj1,{
text3 : {
value : "text3"
}
});
console.log(obj2.text3);//text3
プロパティには値(value)に加えて列挙可能(enumerable)か、削除可能(configurable)か、変更可能(writable)などの属性を合わせて指定ができます。
第2引数のフォーマットは厳格に定義されており以下のように指定した場合エラーに成ってしまうので注意が必要です。
obj1 = {
text1 : "text1",
text2 : "text2"
}
obj2 = Object.create(obj1,{
text3 : "text3"
});
登録日 : 2015年08月30日 最終更新日 : 2015年8月30日
同じカテゴリー(Object)のエントリー
- Object.create()
- Object.getPrototypeOf()
- Object.isFrozen()
- Object.freeze()
- Object.isSealed()
- Object.seal()
- Object.isExtensible()
- Object.preventExtensions()
- Object.getOwnPropertyDescriptor()
- Object.defineProperties()
- Object.defineProperty()
- keys()
- valueOf()
- toString()
- toLocaleString()
- propertyisEnumerable()
- isProtoTypeOf()
- hasOwnProperty
- constructor