LoginSignup
0
0

More than 1 year has passed since last update.

prorotypeって?🍣

Last updated at Posted at 2021-06-26

prototypeとは

prototype 英語:原型の意味
・オブジェクトに存在する特別な"プロパティ"
・コンストラクタ関数と合わせて使用する

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

Person.prototype.hello = function() {
    console.log('hello ' + this.name)
} //コンストラクタ関数(Person)で使用したいメソッドを追加していく


const uni = new Person('uni', 18);
const hamachi = new Person('hamachi', 33);
const fattytuna = new Person('fattytuna', 20);

uni.hello();
hamachi.hello();

出力結果
hello uni
hello hamachi





しかしprototypeを使わなくとも下の書き方でも同じ出力結果を出せる

ex.js
function Person(name, age) {
    this.name = name;
    this.age = age;
    this.hello = function() {
        console.log('hello' + this.name);
    }
}

Person.prototype.hello = function() {
    console.log('hello ' + this.name)
} //コンストラクタ関数(Person)で使用したいメソッドを追加していく


const uni = new Person('uni', 18);
const hamachi = new Person('hamachi', 33);
const fattytuna = new Person('fattytuna', 20);

uni.hello();
hamachi.hello();


prototypeをなぜ使うの??

使わない場合
インスタンスを生成するたびに何度も関数を生成する必要があるのでメモリの消費が多くなる
使う場合
各インスタンスに渡すのはオブジェクトの参照_=参照先は全て一致 =余分なメモリを食わない

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