[JavaScript 5] 객체와 프로퍼티/메소드
객체(Object)
객체지향 언어에서 흔히 쓰이는 객체의 JS 버전 설명이다.
객체와 프로퍼티, 메소드에 대해서는 이미 알고 있으니 부연적인 것만 말해보자면
document와 body와 같은 것들도 객체이다. 그러니 .querySelector()와 같은 메소드가 작동하는 것
코드로 살펴보는 객체의 특징
//ex10.html
var coworkers = {
"programmer" : "egoing",
"designer" : "leezche"
}
document.write("programmer : " + coworkers.programmer + "<br>");
document.write("designer : " + coworkers.designer + "<br>");
coworkers.bookkepper = "duru";
document.write("bookkeeper : " + coworkers.bookkepper + "<br>");
coworkers["data scientist"] = "taeho";
document.write("data scientist : " + coworkers["data scientist"] + "<br>");
배열(array)과 달리 객체는 중괄호로 묶어서 표현한다.
프로퍼티(property)는 따옴표로 묶어서 키(key)와 값(value)을 콜론(:)으로 구분하여 선언한다.
메소드(method)도 같은 방식이지만, 함수명을 먼저 쓰고 콜론 뒤에 function 지시어를 붙인 후 괄호 안에 인자를 넣어주면 된다. (뒤의 개선된 3.html에서 볼 수 있다)
선언 이후에 객체.프로퍼티 식으로 추가 키-값을 입력할 수도 있다. 이때 키가 띄어쓰기를 포함한다면 대괄호 안에 큰따옴표 안에 키를 입력하는 방식으로 만들 수 있다.
//ex10.html
for(var key in coworkers) {
document.write(key + ' : ' + coworkers[key] + '<br>');
}
coworkers.showAll = function() {
for(var key in this) {
document.write(key + ' : ' + this[key] + '<br>');
}
}
coworkers.showAll();
반복문의 인자로 in 키워드를 활용하여 객체 안의 모든 프로퍼티/메소드를 사용할 수 있다. 이때 키는 key로, 값은 객체[key]로 얻을 수 있다.
객체.메소드 식으로 추가 메소드를 입력할 수도 있다. 이때는 등호 뒤에 function() 키워드를 활용하여 선언하면 된다.
버튼 개선
//colors.js
var Body = {
setColor: function(color) {
document.querySelector('body').style.color = color;
},
setBackgroundColor: function(color) {
document.querySelector('body').style.backgroundColor = color;
}
}
var Links = {
setColor: function(color) {
var alist = document.querySelectorAll('a');
var i = 0;
while(i < alist.length) {
alist[i].style.color = color;
i = i + 1;
}
}
}
function nightDayHandler(self) {
var target = document.querySelector('body');
if (self.value === 'night') {
Body.setBackgroundColor('black');
Body.setColor('white');
self.value = 'day';
Links.setColor('powderblue');
} else {
Body.setBackgroundColor('white');
Body.setColor('black');
self.value = 'night';
Links.setColor('blue');
}
}
다음과 같이 객체 Body와 Links를 선언하고, 안에 메소드 setColor()와 setBackgroundColor()를 선언하여 둔다.
이후 버튼을 생성하는 함수 nightDayHandler() 내부의 세팅값들을 객체의 메소드로 대체하면 끝이다.
그런데 주석을 보면 알 듯이 이 파일은 colors.js라는 별도의 자바스크립트 파일로 생성된 것을 알 수 있다. 이 파일을 어떻게 html 코드에 포함시킬 수 있을까?
<!--토글 코드 개선5: 객체 활용 및 js 파일 쪼개기-->
<script src="colors.js"></script>
종전의 head에 선언되어있던 script를 싹 다 지우고, src(source)에 js 파일명을 입력하면 끝이다. 훨씬 유지보수가 간단해졌다!
이하의 버튼 input은 그대로 두면 된다.
출처: [생활코딩!HTML+CSS+자바스크립트 JS편 Chapter 29~34]