객체를 직접 써서 만들 수도 있지만 그렇게 만들면 방대한 양의 객체는 만들어 낼 수 없게 된다.
자바스크립트는 공장에서 물건을 찍어내듯이
주어진 값에 따라 자동적으로 객체를 생성해내는 기능들이 있는데
그런 기능중에 하나가 생성자 함수를 사용하는 것이다.
// 생성자 함수를 사용하지 않으면 일일히 객체를 만들어야한다..
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:10,
sum:function(){
return this.first+this.second+this.third;
}
}
console.log("kim.sum()", kim.sum());
console.log("lee.sum()", lee.sum());
생성자 함수 사용
function Person(name, first, second, third){
this.name=name;
this.first=first;
this.second=second;
this.sum = function(){
return this.first+this.second;
}
}
var kim = new Person('kim', 10, 20);
var lee = new Person('lee', 10, 10);
console.log("kim.sum()", kim.sum());
console.log("lee.sum()", lee.sum());
- 함수명 앞에 new 가 붙으면 이 함수는 이제부터 생성자(constructor) 함수가 된다.
- 객체는 var 참조 변수명 = new 생성자 함수(인자 정보) 형태로 생성한다.
- 속성은 this.속성 = 속성값 형태로 사용된다.
- 함수는 this.함수 = function() {코드} 형태로 사용된다.
- 인자에 정보를 넘겨주면 해당 정보를 프로퍼티에 할당한다.
생성자 함수를 쓸 때 메모리 낭비를 방지하기 위해 프로토타입을 사용할 수 있다.
// 생성자 함수만으로 객체를 만들어 낼 때
function Person(name, first, second, third){
this.name=name;
this.first=first;
this.second=second;
this.sum = function(){
return this.first+this.second;
}
}
var kim = new Person('kim', 10, 20);
var lee = new Person('lee', 10, 10);
// 객체가 만들어졌습니다!
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:10,
sum:function(){
return this.first+this.second+this.third;
}
}
// 자세히 보아하니 모든 객체에서 동일한 sum()이 계속 만들어진다.
// 이것은 곧 메모리 낭비!
프로토타입 사용
function Person(name, first, second, third){
this.name=name;
this.first=first;
this.second=second;
}
// 생성자함수 만들기
Person.prototype.sum = function(){
return 'prototype : '+(this.first+this.second);
}
// 생성자함수를 통해 만들어진 객체는 생성자함수의 프로토타입을 공유하게됨.
// 즉, 똑같은걸 계속 만들 필요 없게 되버림.
// 만약 특정 객체만 공유하고 있는 프로토타입 대신 다른걸 쓰고 싶다면 아래처럼 작성하면 된다.
kim.sum = function(){
return 'this : '+(this.first+this.second);
}
https://opentutorials.org/module/4047/24608
객체 공장 - JavaScript 객체 지향 프로그래밍
수업소개 객체를 수동으로 만드는 가내수공업에서 벗어나서 객체를 자동으로 찍어내는 공장인 constructor을 만들어봅시다. 강의1 가내수공업으로 객체를 만들 때의 단점을 소개합니다. 코드 ob
opentutorials.org
https://opentutorials.org/module/4047/24610
prototype - JavaScript 객체 지향 프로그래밍
수업소개 JavaScript의 prototype이 필요한 이유와 prototype을 통해서 코드의 재사용성과 성능을 향상시키는 방법을 알려드립니다. 강의1 prototype이 필요한 이유를 소개합니다. 강의2 prototype을 이용
opentutorials.org
'자바스크립트' 카테고리의 다른 글
객체지향 프로그래밍 - __proto__ 와 Object.create() (0) | 2021.10.25 |
---|---|
객체지향 프로그래밍 - Class,상속,Super (0) | 2021.10.21 |
객체지향 프로그래밍 - 객체 (0) | 2021.10.19 |
event.preventDefault() (0) | 2021.08.13 |
구조분해할당 (0) | 2021.08.08 |