[생활코딩JavaScript] 06일차 노트정리 (객체, for반복문, 프로퍼티와...

[생활코딩JavaScript] 06일차 노트정리 (객체, for반복문, 프로퍼티와...

객체 예고

'객체(Object)'

function setColor(color){ document.querySelector('body').style.color = color; } setColor('white');

함수의 이름이 중복되게 않게 해야한다.

ex) Body SetColor(color)

SetColor(color) ex) Head SetColor(color)

SetColor(color) ex) LineSetColor(color)

"서로 연관된 함수와 변수를 그루핑해서 정리 정돈하기 위한 수납상자로서 객체라는 것이 존재한다."

객체 쓰기와 읽기

배열과 객체의 차이

배열 정보가 순서대로 저장된다는 특징을 가지고 있다. 대괄호를 사용한다 []

객체 정보가 순서 없이 저장된다. 중괄호를 사용한다 {}

객체의 문법

객체를 만들 때 사용하는 기호를 객체 리터럴(Object literal)이라고 합니다.

var coworkers = { "programmer":"egoing", "besigner":"leezche" }

와 같이 객체에 정보를 담았습니다.

document.write(coworkers.programmer+""); document.write(coworkers.desinger+"");

객체 접근 연산자(Object Access Operator) : ( . )

을 사용하여 객체와 key를 입력하여 value값을 받아올 수 있습니다.

coworkers.bookkeeper = "duru";

위와 같이 새로운 key값을 지정하여, value값을 입력해주면 객체 내부에 새로운 정보가 입력이 됩니다.

coworkers.data scientist = "taeho";

위와 같은 경우에는 key값이 data scientist로 공백이 존재합니다 이 경우에는 문법적 오류 라고 할 수 있습니다.

이런 경우에는 대괄호를 사용해서 문자열 형태로 넣으면 똑같은 효과를 가져올 수 있습니다.

coworkers["data scientist"] = "taeho";

이렇게 말입니다!

객체와 반복문

var coworkers = { "programmer":"egoing", "besigner":"leezche" } //모든 value값 호출 for(var key in coworkers){ }

coworkers의 모든 객체를 꺼내서 화면에 출력하는 코드를 위와 같이 작성합니다.

var coworkers = { "programmer": "egoing", "besigner": "leezche" } coworkers.name = "YangGeng"; for (var key in coworkers) { document.write("key: " + key + "
" + "value: " + coworkers[key] + "

"); }

결과

객체 프로퍼티와 메서드

객체는 함수도 담을 수 있다.

coworkers.showAll = function(){ }

위 코드는 showAll이라는 메서드를 추가하는 코드입니다. 위의 코드는 function showAll(){ }과 똑같은 표현이라고 보면 됩니다.

coworkers.showAll(); //coworkers객체에 있는 showAll()메서드 호출

var coworkers = { "programmer": "egoing", "besigner": "leezche" } coworkers.name = "YangGeng"; coworkers.showAll = function(){ for (var key in coworkers) { document.write("key: " + key + "
" + "value: " + coworkers[key] + "

"); } } coworkers.showAll();

결과

위의 코드는 객체에 showAll이라는 메서드를 추가하고 마지막에 메서드를 호출하여 객체의 key값과 value값이 모두 호출 되었다.

그러나 위의 코드는 좋은 방법이 아니다, 왜냐하면 coworkers의 이름이 showAll()함수 내에도 있기 때문에 coworkers라는 객체의 이름이 바뀐다면 showAll()함수에서 데이터를 가져오지 못하는 현상이 생길 수 있다.

coworkers라는 객체 이름 대신 this를 사용

var coworkers = { "programmer": "egoing", "besigner": "leezche" } coworkers.name = "YangGeng"; coworkers.showAll = function(){ for (var key in this) { document.write("key: " + key + "
" + "value: " + this[key] + "

"); } } coworkers.showAll();

이로서 변수명이 다른 것으로 바뀌어도 this는 자기 자신을 가리키기 때문에 영향을 받지 않는다는 장점이 생겼다.

메서드(method) : 객체에 소속된 함수

: 객체에 소속된 프로퍼티(property) : 객체에 소속된 변수

객체의 활용

생활코딩 var Body = { setColor : function(color){ document.querySelector("body").style.color = color; }, //객체에 정보를 추가할때 마다 반드시 콤마(,)를 입력할 것 setBackgroundColor : function(color){ document.querySelector("body").style.backgroundColor = color; } } function nightDayHandler(self) { if (self.value === 'night mode') { Body.setBackgroundColor('black'); Body.setColor('white'); self.value = 'day mode'; var alist = document.querySelectorAll('a'); i = 0; while (i < alist.length) { alist[i].style.color = 'yellow'; i += 1; } } else { Body.setBackgroundColor('white'); Body.setColor('black'); self.value = 'night mode'; var alist = document.querySelectorAll('a'); i = 0; while (i < alist.length) { alist[i].style.color = 'red'; i += 1; } } }

지난 시간에 작성한 코드를 오늘 배운 객체를 이용해 좀더 단순하고 편리하게 바꾸어 보았습니다.

from http://ygscoding1193.tistory.com/20 by ccl(A) rewrite - 2021-11-19 04:28:19