0
0

More than 1 year has passed since last update.

【JavaScript】関数とオブジェクト⑪  new演算子

Posted at

はじめに

Udemyの【JS】ガチで学びたい人のためのJavaScriptメカニズムの講座の振り返りです。

前回の記事

目的

  • 関数とオブジェクトについての理解を深める

本題

1.new演算子

new演算子とはコンストラクター関数からインスタンスを作成するための演算子のこと

例1

コンストラクター関数の戻り値がreturnで、オブジェクトになっている場合

// 関数を定義
function F(a,b){
  this.a = a;
  this.b = b;
  // 戻り値にreturnで、空のオブジェクトを設定
  return {};
}
// インスタンス化
const instance = new F(1,2);
// この結果を出力すると{}からのオブジェクトが出力される
console.log(instance);
// 戻り値{}がFに返ってきているから??

オブジェクトではなくプリミティブ型で戻り値を設定すると

function F(a,b){
  this.a = a;
  this.b = b;
  // オブジェクトではなくプリミティブ型で戻り値を設定
  return 1;
}
const instance = new F(1,2);
// 実行結果はF {a: 1, b: 2}となる
console.log(instance);

// returnを消しても同様の結果

prototypeで定義してみる

function F(a,b){
  this.a = a;
  this.b = b;
}

F.prototype.c = function(){}

const instance = new F(1,2);
console.log(instance);
実行結果.
F {a: 1, b: 2}a: 1b: 2
[[Prototype]]: Object
 c: ƒ ()
 constructor: ƒ F(a,b) 
 [[Prototype]]: Object

[[Prototype]]: Objectの中にcが入っている

例2 

new演算子を呼び出す

function F(a,b){
  this.a = a;
  this.b = b;
  return {};
}

F.prototype.c = function(){}

// 第一引数をコンストラクタの「C」として定義
// 第二引数以下はコンストラクタ関数の引数によって変わってくるので...(レストパラメーターズ)と
// 可変長の引数(固定ではなく任意の個数の引数)を表すためにargsを使用
function newOpe(C, ...args){
  // 出力結果は以下の通り(上記のように表すと引数が配列として返ってくる)
  console.log(args);
}

// F(1,2)を削除し、新たにnewOpeという関数を定義
// 第一引数にコンストラクタ関数
const instance = newOpe(F,1,2)
console.log(instance);
Console.
(2) [1, 2]
 0: 1 
 1: 2 
 length: 2 
[[Prototype]]: Array(0)

例3

thisが呼び出し元のオブジェクトのインスタンスになる場合

function F(a,b){
  this.a = a;
  this.b = b;
  // return {};
}

// thisというオブジェクトをprototypeの参照を保持したまま生成する
F.prototype.c = function(){}

function newOpe(C, ...args){
  // 空のオブジェクト_thisを定義 createメソッドを使って渡ってきたCのprototypeをコピー
  const _this = Object.create(C.prototype);
  // Cを実行するとき_thisは関数Fのオブジェクト,argsは配列としてa,bが渡ってきている
  // それを変数resultに格納
  const result = C.apply(_this, args);
  console.log(result, _this);
  // 戻り値でnewOpeに_thisの値を返す
  return _this;
}

const instance = newOpe(F,1,2);
// 実行結果がF {a: 1, b: 2}となる
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