객체
함수의 기반 위에서 존재하는 개념. 서로 연관된 함수와 변수가 아주 많아지면 이를 정리하기 위해서 사용.
하이퍼 링크 색깔을 바꾸는 코드를 함수화.
function LinksSetColor(color){
var alist = document.querySelectorAll('a');
var i = 0;
while(i < alist.length){
alist[i].style.color= 'color';
i += 1;
}
}
배경과 글자색을 바꾸는 코드 함수와
function BodySetColor(color){
document.querySelector('body').style.color= 'color';
}
function BodySetBackgroundColor(color){
document.querySelector('body').style.backgroundColor= 'color';
}
함수들 간에는 중복된 이름을 사용하지 않는다. 함수가 많아질 수록 이름이 복잡해진다.
이와 같이 다양한 함수가 존재하는 상황에서 객체를 사용하게 된다.
객체는 폴더와 같은 개념으로 서로 다른 객체에 속한 함수는 이름이 중복 되어도 상관없다.
객체의 예시.
document.querySelector('body');
위 코드에서 document 는 객체이다. querySelector 는 document에 속해있는 함수이다.
객체에 속해있는 함수를 메소드(Method)라는 별도의 이름으로 부른다.
객체 읽기와 쓰기
객체는 순서가 없는 대신 각각의 이름이 붙어 있고, 이름을 통해 값을 꺼내온다.
객체의 문법
객채는 중괄호를 사용해 만든다. 각각의 요소들은 ' 이름과 값 ' 으로 이루어져 있다.
var arr = {
"furit" : "apple",
"hero" : "Batman",
"villain" : "Joker"
};
이 코드에서 apple 이란 값은 fruit 라는 이름을 갖고 있다.
요소추출
document.write(arr.hero);
document.write(arr['hero']);
요소추가
arr.movie = "곡성";
arr["movie two"] = "랑종"; // 이름에 공백이 있을 경우
이름에 공백이 있을 경우 대괄호로 묶어준다.
객체의 순회(iteration)
객체에서는 for in 을 사용해 순회 한다.
var arr = {
"furit" : "apple",
"hero" : "Batman",
"villain" : "Joker"
};
for(var key in arr){
document.write(key +'<br>');
}
document.write('<br>');
for(var key in arr){
document.write(key+' : '+arr[key]+'<br>');
}
for을 사용하면 arr에 있는 이름을 하나씩 가져와서 key에 넣어준다.
객체의 프로퍼티와 메소드
객체에 새로운 메소드 추가
arr에서만 사용할 수 있는 showAll() 메소드 추가.
arr.showAll=function(){
for(var key in arr){
document.write(key+' : '+arr[key]+'<br>');
}
}
이 코드는 arr 이라는 변수 이름이 바뀌면 함수를 수정 해야 되기때문에 좋은 방법이 아니다.
this를 사용하면
<변경>
arr.showAll=function(){
for(var key in this){
document.write(key+' : '+this[key]+'<br>');
}
}
this는 이 메소드가 쓰인 객체를 가리킨다.
showAll()은 객체의 데이터 이므로 화면에 표시됨.
arr.showAll=function(){
for(var key in this){
if(key === 'showAll'){
document.write('<br>');
}
else {
document.write(key+' : '+this[key]+'<br>');
}
}
}
메소드 : 객체에 해당하는 함수들.
프로퍼티(Property) : 객체에 해당하는 변수들. (arr.hero 에서 hero에 해당함.)
프로퍼티와 프로퍼티는 콤마(,)로 구분한다.
객체의 활용
<script>
function nightdayhandler(self){
if(self.value === 'night'){
document.querySelector('body').style.backgroundColor= 'black';
document.querySelector('body').style.color= 'white';
self.value = 'day';
var alist = document.querySelectorAll('a');
var i = 0;
while(i < alist.length){
alist[i].style.color= 'powderblue';
i += 1;
}
}
else{
document.querySelector('body').style.backgroundColor= 'white';
document.querySelector('body').style.color= 'black';
self.value = 'night';
var alist = document.querySelectorAll('a');
var i = 0;
while(i < alist.length){
alist[i].style.color= 'blue';
i += 1;
}
}
}
</script>
<h1><a href="#">배열과 반복문의 활용</a></h1>
<ol>
<li><a href="#">A</a></li>
<li><a href="#">B</a></li>
<li><a href="#">C</a></li>
</ol>
<input type="button" value="night" onclick="
nightdayhandler(this); ">
<p>AAAAAAAAAAAAAAAAAAAAAAAAAAA</p>
<p>AAAAAAAAAAAAAAAAAAAAAAAAAAA</p>
<p>AAAAAAAAAAAAAAAAAAAAAAAAAAA</p>
<p>AAAAAAAAAAAAAAAAAAAAAAAAAAA</p>
<p>AAAAAAAAAAAAAAAAAAAAAAAAAAA</p>
이 코드는 겹치는 부분이 많다 따라서 객체를 활용해 문제점을 해결한다.
Body라는 이름의 객체를 만든다.
var Body = {
setColor:function(color){
document.querySelector('body').style.backgroundColor= color;
}
setBackgroundColor:function(color){
document.querySelector('body').style.color= color;
}
};
Links라는 객체를 만든다.
var Links = {
setColor:function(color){
var alist = document.querySelectorAll('a');
var i = 0;
while(i < alist.length){
alist[i].style.color= color;
i += 1;
}
}
}
<script>
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 += 1;
}
}
}
function nightdayhandler(self){
if(self.value === 'night'){
Body.setBackgroundColor('black');
Body.setColor('white');
Links.setColor('powderblue');
self.value = 'day';
}
else{
Body.setBackgroundColor('white');
Body.setColor('black');
Links.setColor('blue');
self.value = 'night';
}
}
</script>
<h1><a href="#">배열과 반복문의 활용</a></h1>
<ol>
<li><a href="#">A</a></li>
<li><a href="#">B</a></li>
<li><a href="#">C</a></li>
</ol>
<input type="button" value="night" onclick="nightdayhandler(this);">
<p>AAAAAAAAAAAAAAAAAAAAAAAAAAA</p>
<p>AAAAAAAAAAAAAAAAAAAAAAAAAAA</p>
<p>AAAAAAAAAAAAAAAAAAAAAAAAAAA</p>
<p>AAAAAAAAAAAAAAAAAAAAAAAAAAA</p>
<p>AAAAAAAAAAAAAAAAAAAAAAAAAAA</p>
이 코드에서 Body.setColor('black'); 와 Links.setColor('blue'); 은 함수 이름이 같다. 하지만 충돌은 일어나지 않는다.
충돌이 일어나지 않는 이유는 서로 다른 객체에 소속된 메소드 이기 때문이다.
'정리' 카테고리의 다른 글
[자바스크립트의 시작] (8) Javascript 객체 기본 (0) | 2021.08.26 |
---|---|
[자바스크립트의 시작] (7) Javascript 활용 (0) | 2021.08.25 |
[자바스크립트의 시작] (5) Javascript 함수 (0) | 2021.08.24 |
[자바스크립트의 시작] (4) Javascript 제어문 배열과 반복문 (0) | 2021.08.23 |
[자바스크립트의 시작] (3) Javascript 제어문 리팩토링(중복제거) (0) | 2021.08.23 |