prototype function vs. method function

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
function Person(name, nickname) {
this.name = name;
this.nickname = nickname;

// method function
this.sayHi = function () {
console.log(this.name, this.nickname, 'hello', this);
};
}

const sung = new Person('sung', 'superpower');
const sung2 = new Person('sung', 'superpower');

console.log(sung.sayHi === sung2.sayHi); // false

Person.prototype.sayHello = function () {
console.log('sayHello prototype');
console.log(this.name, this.nickname, 'hello', this);
};

console.log(sung.sayHello === sung2.sayHello); // true
  • 생성자가 실행될때마다 새로운 메서드 함수가 생성된다
  • 프로토타입으로 정의된 함수는 모든 인스턴스가 하나의 함수를 바라본다

참고