1
0

More than 1 year has passed since last update.

JavaScriptのコンストラクタとプロトタイプの違いについて

Posted at

コンストラクタ

function Dog(name, cry) {
  this.name = name;
  this.bark = function() {
    console.log(cry);
  };
}
var dog = new Dog('きなこ', 'わんわん');
console.log(dog.name); // きなこ
dog.bark(); // わんわん

上記のコードでnewを取り除くとエラーが発生する。この違いは何か?実は暗黙のルールで二行加わっています。

function Dog(name, cry) {
  // var this = {};
  this.name = name;
  this.bark = function() {
    console.log(cry);
  };
  // return this;
}

newをつけない場合はself等を用意しなくてはならない

function Dog(name, cry) {
  var self = {};
  self.name = name;
  self.bark = function() {
    console.log(cry);
  };
  return self;
}

var dog = Dog('きなこ', 'わんわん');
console.log(dog.name); // きなこ
dog.bark(); // わんわん

プロトタイプ

プロトタイプとは「オブジェクト」のことであり、親の能力は子にも受け継がれている的なニュアンス

prototypeとは?

prototypeプロパティを利用することで、オブジェクトにメソッドやプロパティを定義することが可能にする

const Member = function (firstName, lastName) {
  this.firstName = firstName;
  this.lastName = lastName;
}

Member.prototype.getName = function () {
  return this.firstName + this.lastName;
}

const mem1 = new Member('田中', '太郎');
const mem2 = new Member('山田', '二郎');
console.log(mem1.getName());
console.log(mem2.getName());

上と下では表示結果は同じ

function Dog() {}
Dog.prototype.bark = function() {
  console.log('わんわん');
};

var dog = new Dog();
dog.bark(); //'わんわん';

------------------------

function Dog() {
  this.bark = function() {
    console.log('わんわん');
  };
}
var dog = new Dog();
dog.bark(); //'わんわん';

しかし、下はnewはこんな暗黙のルールで余計な記述が作られる。そのため毎回空オブジェクトを作成し、毎回新しくbark関数を定義している

function Dog() {
  // var this = {};
  this.bark = function() {
    console.log('わんわん');
  };
  // return this;
}

2つ以上インスタンスを作る時はプロトタイプの出番

function Dog(cry) {
  this.cry = cry;
}
Dog.prototype.bark = function() {
  console.log(this.cry);
};

const chiwawa = new Dog('きゃんきゃん');
chiwawa.bark(); //'きゃんきゃん';

const shiba = new Dog('わんわん');
shiba.bark(); //'わんわん';

使わない場合は下記のようなコードになる

function Dog(cry) {
  this.cry = cry;
      this.bark = function() {
      console.log(this.cry);
    };
}

const chiwawa = new Dog('きゃんきゃん');
chiwawa.bark(); //'きゃんきゃん';

const shiba = new Dog('わんわん');
shiba.bark(); //'わんわん';
1
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
1
0