LoginSignup
0
0

More than 1 year has passed since last update.

【JavaScript】関数とオブジェクト⑩ prototype

Last updated at Posted at 2021-10-25

はじめに

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

前回の記事

目的

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

本題

1.プロトタイプとは

  • コンストラクター関数と一緒に使用する
  • オブジェクトに存在する特別なプロパティのこと
  • インスタンス化した際にprototypeの参照がprotoにコピーされる

例1

function Person(name, age) {
    this.name = name;
    this.age = age;
}

// 以下にコンストラクター関数のメソッドを追加し無名関数を代入
Person.prototype.hello = function(){
    // Personのthis.nameを入れる
    console.log("Hello" + this.name);
}

const bob = new Person('Bob', 18);
const tom = new Person('Tom', 33);
const sun = new Person('Sun', 20);

// 実行するとHelloBobと出力
bob.hello();

メソッドとして使いたいプロパティをプロトタイプに格納するとインスタンスごとに関数を実行できる
→ ないとエラーになった!

例2

thisにhelloメソッドを登録した場合

function Person(name, age) {
    this.name = name;
    this.age = age;
    this.hello = function(){
        console.log("Hello" + this.name);
    }
}

const bob = new Person('Bob', 18);
const tom = new Person('Tom', 33);
const sun = new Person('Sun', 20);

// 実行するとHelloBobと出力
bob.hello();
tom.hello();
sun.hello();

Prototypeを使わなくても実行できる
メモリの消費を抑えるためにprotoypeを使用する

今日はここまで!

参考にさせて頂いた記事

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