LoginSignup
0
0

More than 1 year has passed since last update.

オブジェクト
return { }
新しくオブジェクトが生成される
オブジェクト以外
proto
prototypeをコピー

return付きのコンストラクターを生成時の挙動の違いについて

<条件1-1>

1.return 内が空の{}→空のオブジェクトが生成
2.オブジェクト内のthisにプロパティを設定→undefindが返される
3.プロトタイプを指定→__proto__には保存されていない

function F(a,b){
 this.a = a;
 this.b = b;
 return {};
}
F.prototype.c = function(){console.log("C")}
const ins = new F(1,2);

console.log(ins); 
console.log(ins.a); 
console.log(ins.b); 
console.log(ins.c);  

スクリーンショット 2022-09-05 14.27.42.png

<条件1-2>

1.return 内に{キー:バリュー}→オブジェクトが生成
2.オブジェクト内のthisにプロパティを設定→undefindが返される
3.プロトタイプを指定→__proto__には保存されていない

function F(a,b){
 this.a = a;
 this.b = b;
 return {d:2,e:4};
}
F.prototype.c = function(){console.log("C")}
const ins = new F(1,2);

console.log(ins); 
console.log(ins.a); 
console.log(ins.b); 
console.log(ins.c); 

スクリーンショット 2022-09-05 14.19.05.png

<条件2>

1.return 内が値値が生成
2.オブジェクト内のthisにプロパティを設定thisが設定される
3.プロトタイプを指定__proto__に処理が設定される
function F(a,b){
 this.a = a;
 this.b = b;
 return 1;
}
F.prototype.c = function(){console.log("C")}
const ins = new F(1,2);

console.log(ins); 
console.log(ins.a); 
console.log(ins.b); 
console.log(ins.c); 

プロトタイプを切り離してオブジェクトをコピーする方法

1.プロトタイプをコピー C.prototype
2.オブジェクトを生成 Object.create
3.2を空の_thisに代入
4.applyオブジェクトで__thisに格納する
https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/Function/apply

function F(a,b){
 this.a = a;
 this.b = b;
}
F.prototype.c = function(){console.log("C")}
const ins = new F(1,2);

console.log(ins); 
console.log(ins.a); 
console.log(ins.b); 
console.log(ins.c); 

function newOpe(C,...args){
	const _this = Object.create(C.prototype);
    C.apply(_this,args);
	console.log(result,_this)
}

const instance = newOpe(F,2,30)
console.log(instance)
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0