[JS] 4. 객체(Objects)
1. 객체란
- 객체는 연관된 데이터, 연관된 함수의 모음이다.
- 객체는 여러 변수와 여러 함수로 구성되며, 이들은 객체 내부에 있을 때 속성(property)과 메소드(method)라고 부른다.
- 객체는 순서가 없는 대신 이름으로 값을 저장한다.
2. 객체 생성하고, 추가하고, 가져오고, 삭제하는 방법
- 생성
var ObjectName = { } ;
// 객체 생성
var fruits = {
"banana":"yellow",
"apple":"red"
};
- 추가 및 수정
// 점 표기법(dot notation)
fruits.kiwi = "green";
// 괄호 표기법(Bracket notation)
fruits["blue berry"] = "purple";
- 접근(읽기)
// 점 표기법(dot notation)
fruits.banana ;
// 괄호 표기법(Bracket notation)
fruits["blue berry"] ;
- 삭제
delete fruits.banana ;
3. 객체 순회(for in)
- 객체는 순서가 없는데 데이터를 어떻게 반복할까?
- 객체데이터를 순회하는 방법으로 속성에 대해 반복한다.
for (var variable in object) {
statement ;
}
// 위의 예제
for (var key in fruits) {
document.write(key+" : "+fruits[key]+"<br>");
} // fruits[key], 즉, 배열의 방법 O (fruits.key처럼 object.변수는 성립x)
// output
banana : yellow
apple : red
kiwi : green
blue berry : purple
4. this
- this란 this가 속해있는 함수(method)가 속해있는 객체를 가리킨다. (자신이 속한 객체의 대명사처럼 쓰임)
- this를 사용하면 객체 이름이 수정되어도 자기자신을 의미하므로, 수정이 용이하다.
5. Constructor (생성자)
- constructor 은 객체를 생성하는 함수(method)이다.
- 보통 객체를 생성할 때마다 객체에 대한 정의가 필요하지만, new 키워드를 사용하면 실행할 때마다 객체가 양산되는 '생성자'가 만들어 진다. (객체의 초기 상태를 정의한다.)
- 생성자의 코드를 바꾸면 생성자로 인해 만들어진 모든 객체의 코드도 한번에 바뀌므로 유지보수에 용이하다.
// Score라는 객체를 생성한다. Score객체 내부에는 sum이라는 함수를 만들었다.
function Score(name, a, b, c){ // 객체의 초기 상태 셋팅
this.name=name,
this.a=a,
this.b=b,
this.c=c,
Score.prototype.sum = function() {
return this.a+this.b+this.c;
}
}
document.write(Score()+'<br>'); // undefined
document.write(new Score())+'<br>'; // [object Object]
// new 키워드를 사용하여 객체를 양산한다.
var test1 = new Score('test1',10,20,15);
var test2 = new Score('test2',20,15,25);
document.write(test1.sum()+'<br>'); // 45
document.write(test2.sum()+'<br>'); // 60
- 위의 코드에서 객체를 양산할 때마다 sum이라는 함수를 반복해서 호출하기 때문에 내부메모리를 불필요하게 사용하게 된다.
- 그러므로 prototype을 이용하여 생성자 객체의 공통된 특성을 정의하는 것이 일반적인 constructor 패턴이다.
- 아래처럼 prototype을 이용하여 생성자 내부에서 외부로 함수를 빼내면 한번만 호출하면 되므로 메모리를 절약할 수 있다.
function Score(name, a, b, c){
this.name=name,
this.a=a,
this.b=b,
this.c=c
}
Score.prototype.sum = function() {
return this.a+this.b+this.c;
}
var test1 = new Score('test1',10,20,15);
var test2 = new Score('test2',20,15,25);
document.write(test1.sum()+'<br>'); // 결과값은 동일, 45
document.write(test2.sum()+'<br>'); // 결과값은 동일, 60
이 글은 부스트코스[자바스크립트의 시작_생활코딩] 강의 수강 후 개인 공부용으로 작성한 글입니다.
참고)