JS #5 객체
객체는 정리 정돈.
서로 연관된 함수, 변수를 grouping.
객체{}는 배열[]과 달리 순서가 없다.
var coworkers = {
"programmer" : "egoing",
"designer" : "leezche"
};
document.write(coworkers.programmer);
또는
document.write(coworkers["programmer"]);
출력
egoing.
객체 추가 시,
coworkers.bookkeeper = "duru";
또는
coworkers["bookkeeper"] = "duru";
는
var coworkers = {
"programmer" : "egoing",
"designer" : "leezche",
"bookkeeper" : "duru"
};
로 추가
객체 내 모든 원소 가져오기. for 문 사용
for(var key in coworkers){
document.write(coworkers[key]);
}
객체 함수 추가.
coworkers.showAll = function(){
}
는
var showAll = function{
}
이나
function showAll(){
}
과 동일.
coworkers.showAll = function(){
for(var key in this){
document.write(this[key]);
}
}
여기서 this는 coworkers 객체 의미.
객체에 소속된 함수를 method라고 한다.
객체에 소속된 변수(programmer 등)를 property라고 한다.
활용
var Body = {
setColor:function (color){
document.querySelector('body').style.color = color;
},
setBgcolor:function (color){
document.querySelector('body').style.backgroundColor = color;
}
}
객체와 함수 지정 후,
Body.setColor('white');
등으로 사용.