JavaScript

Object.create()メソッド

 編集:2023.02.02 by T.A.

[Edge]。→

構文
Object.create(proto[, propertiesObject] )
proto 生成するオブジェクトのプロトタイプになるべきオブジェクト。null または Object(プリミティブ ラッパー オブジェクト(値を含むオブジェクト)を除く)。
properties 省略可。追加するプロパティと定義データのオブジェクト。→Object.defineProperties():props
戻り値

新しい Object オブジェクト。

例外
TypeError
proto のタイプが違う。
//proto
D=Object.create({});  //={}(Object)
	//=[object]:[object Object]
D.p=10;              //
//D =[object]:[object Object]
	//p=[number]:10

D=Object.create(null);  //エラー発生:Cannot convert object to primitive value
D=Object.create(undefined);  //エラー発生:Object prototype may only be an Object or null: undefined
D=Object.create();  //エラー発生:Object prototype may only be an Object or null: undefined
	//オブジェクト プロトタイプは、オブジェクトまたは null のみにすることができます
D=Object.create({null});  //エラー発生:Unexpected token 'null'
//propertiesObject
D=Object.create({p1:10}, {p2:{value:20}});  //p1=10(プロトタイプ)、p2=20。
	//=[object]:[object Object]
	//p1=[number]:10。p2が列挙できない。
//D.p1 =[number]:10
//D.p2 =[number]:20
D.p2="あ";
//D.p2 =[number]:20。変更できない。

D=Object.create({p1:10}, {p2:{value:20, writable:true}});  //p1=10(プロトタイプ)、p2=20(書き込み可)。
	//=[object]:[object Object]
	//p1=[number]:10
D.p2="あ";
//D.p2 =[string]:あ。書き込めた。

//読めないプロパティを読んでみる
D=Object.create({p1:10}, {p2:{value:20}});  //p1=10(プロトタイプ)、p2=20。
	//=[object]:[object Object]
	//p1=[number]:10。p2が列挙できない。
//D.p2 =[number]:20
DA=Object.getOwnPropertyDescriptors(D);  //全てのプロパティ記述子を得る。
	//=[object]:[object Object]
	//p2=[object]:[object Object]
//DA.p2 =[object]:[object Object]
	//value=[number]:20
	//writable=[boolean]:false
	//enumerable=[boolean]:false
	//configurable=[boolean]:false

getOwnPropertyDescriptors()

古典的な継承
function C(){
  this.x = 0;
}
C.prototype.test=function(x){  //testに処理を割り当て。
  this.x += x+2;
};
function F(){
  C.call(this);
DA=this;  //=[object]:[object Object]
	//x=[number]:12
	//test=[function]:function(x){ //testに処理を割り当て。 this.x += x+2; }
alert(this);  //表示:[object Object]
alert(this.x);  //表示:0
alert(this.test);  //表示:function(x){  //testに処理を割り当て。
	//  this.x += x+2;
	//}
}
F.prototype=Object.create(C.prototype);  //Cから継承。
R=new F();
R.test(10);
D=R.x;  //=[number]:12

Function.call()


テスト