- 함수형 프로그래밍에서 함수의 개수가 많아지면 중복된 함수명을 피하기 위해 함수명이 길어지고 가독성이 좋지 않다.
- 때문에 함수와 변수를
key:value형식으로 모아 분류하는 것을 만들었다. 이것이 객체이다.
var coworkers = { "programmer":"egoing", "designer":"leezche" };
- 이렇게 key와 value의 형태로 나타낸다. javascript에서는 이를 객체라고 한다.
- python의 dictionary와 비슷한 기능이다.
- 어떠한 동작을 하는 함수는 그 대상이 무엇이든 같은 함수명을 사용할 수 있다.
- 이는 객체는 구분되기 때문, 즉 같은 파일명이어도 디렉토리가 다르면 괜찮은 것처럼!
var coworkers = { "programmer":"egoing", "designer":"leezche" }; coworkers.bookkeeper = 'duru'; coworkers["data scientist"] = 'taeho';
- 한 단어면 속성을 정의하듯이
객체.key = value로 저장 - 띄어쓰기가 있다면
객체[key] = value로 저장 - 역시 dictionary와 닮았다.
- 객체의 항목에는 순서가 없다.
- 객체의 모든 항목을 하나씩 조회하는 방법 : for ... in
객체의 모든 항목을 조회해서 처리하려면 아래의 과정을 거쳐야 한다.
<< 불필요한 반복 >> var coworkers = { "programmer": "egoing", "designer": "leezche", "bookkeeper": "duru", "data scientist": "taeho", } document.write('programmer : ' + coworkers.programmer + '<br />'); document.write('designer : ' + coworkers.designer + "<br />"); document.write("bookkeeper : "+coworkers.bookkeeper+"<br />") document.write("data scientist : "+coworkers["data scientist"]+"<br />")
하지만 너무 반복적이고 중복되는 코드가 많기 때문에 비효율적이다. 이를 for in을 이용해 해결한다.
var coworkers = { "programmer": "egoing", "designer": "leezche", "bookkeeper": "duru", "data scientist": "taeho", } for(var key in coworkers){ document.write(key + " : " +coworkers[key]+ "<br />") }
객체 내의 모든 key를 하나씩 찾아 그것으로 어떠한 작업을 할 수 있다.
- Method : 객체에 소속된 함수
- Property : 객체에 소속된 변수(programmer, designer..)
위에서 객체에 소속된 함수가 Method라고 했다. 어떻게 하는지 살펴보자.
coworkers.showAll = function(){ for(var key in this){ document.write(key + " : " + this[key] + "<br />") } } coworkers.showAll();
기존에 객체.key = value 식으로 객체에 항목을 추가한 것처럼 객체.key = function(){...} 의 개념으로 추가할 수 있다.
여기서 반복객체 이름으로 this를 사용하는 이유는 객체의 이름이 바뀌더라도 자기 자신을 조회하는 것이기 때문이다.
var coworkers = { showAll: function(){ for(var key in this){ document.write(key + " : " + this[key] + "<br />") } } }
또 다른 방식으로는 객체가 생성될 때 아예 처름에 function을 넣어버리는 것이다.
