var kim = {
name: 'kim',
first: 10,
second: 20,
sum:function(){
return this.first + this.second;
}
}
var lee = {
name: 'lee',
first: 10,
second: 10,
sum:function(){
return this.first + this.second;
}
}
비슷한 구조의 객체를 동시에 수정하고 싶을 때, constructor가 없으면 아래와 같이 일일히 수정해줘야 한다... 이런 객체가 수억개가 있다면 매우 큰 품이 들 것. 그래서 등장한 것이 constructor!
var kim = {
name: 'kim',
first: 10,
second: 20,
third: 30,
sum:function(){
return this.first + this.second + this.third;
}
}
var lee = {
name: 'lee',
first: 10,
second: 10,
third: 30,
sum:function(){
return this.first + this.second + this.third;
}
}
const d1 = new Date('2021-5-26');
console.log(d1.getFullYear())
console.log(d1.getMonth())
2021-5-26
이라는 데이터를 가진 객체가 생성되어 d1
이 된다.getFullYear
, getMonth
라는 메소드를 실행function Person(name, first, second, third){
this.name = name,
this.first = first,
this.second = second,
this.third = third,
this.sum =function sum(){
return this.first + this.second + this.third;
}
}
const kim = new Person('kim', 10, 20, 30);
const lee = new Person('lee', 10, 10, 10);
console.log(kim);
console.log(lee.sum());
JavaScript는 Prototype 기반의 언어이다!
function Person(name, first, second, third){
this.name = name,
this.first = first,
this.second = second,
this.third = third,
this.sum =function sum(){
return this.first + this.second + this.third;
}
}
위 객체에서 사용된 메소드를 수정하고 싶을 때, 해당 constructor에서 생성된 모든 객체들의 메소드를 아래와 같이 하나하나 바꿔줘야 한다.
kim.sum = function(){
return 'modified : '+(this.first + this.second + this.third)
}
이렇게 하면 매우 비효율적이기 때문에 모든 객체가 공통적으로 사용되는 함수를 만들어줄 필요가 있다. 이때 사용되는게 Prototype!
즉, Prototype은 인스텐스가 사용할 수 있는 메소드를 저장하는 곳이다. 이는 객체가 생성될 때마다 해당 객체의 메소드를 만들어 메모리에 할당하는 대신, 생성자의 프로토타입에 정의함으로써 모든 객체들이 참조하여 사용할 수 있도록 하여 메모리를 효율적으로 사용할 수 있도록 한다.
Person.prototype.sum =function (){
return this.first + this.second + this.third;
}
console.log(kim.sum()); //60
console.log(lee.sum()); //30
Prototype을 이용하면 인스턴스 각각의 메소드에 대한 수정이 필요할 때, 아래와 같이 오버라이딩 할 수 있는 장점이 있다!
kim.sum = function(){
return 'this: ' + (this.first + this.second + this.third);
}
console.log(kim.sum()); //this: 60