생활코딩/JavaScript

200807 6일차 정리 - 객체, 메소드, 프로퍼티

imname1am 2020. 8. 7. 23:46
반응형

객체

  • 객체    ; 폴더의 관점. (이름이 있는 정리정돈 상자). 중괄호 { } 써줌 (배열에서는 대괄호[ ])
  • 메소드 : 객체에 소속된 함수
  • 프로퍼티 : 객체에 소속된 변수

(예)

document.querySelector('body').style.color = color;

① 객체 만들기

(예1)

var coworkers = {
    "programmer" : "egoing",
    "designer" : "leezche"
}; 
  • coworkers                      object access operator. 
  • programmer, designer key (배열에서는 index)
  • egoing, leezche           coworkers[key]

(예2)

var Body = {
    setColor:function(color){
        document.querySelector('body').style.color = color;
    },
    setBackgroundColor:function(color){
        document.querySelector('body').style.backgroundColor = color;
    },
}

: 호출 시 Body.setColor('white');

② 객체 불러오기

document.write("programmer : " + coworkers.programmer + "<br>");

③ 객체 추가하기

- 띄어쓰기 없을 때

coworkers.bookkeeper = "duru";

- 띄어쓰기 있을 때

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

: 불러올 때도  document.write("data scientist : " + coworkers["data scientist"] + "<br>");

④ 객체의 데이터 순환하기

for(var key in coworkers) {
    document.write(key + ' : ' + coworkers[key] + "<br>");
}

 

프로퍼티와 메소드

coworkers.showAll = function(){
    for(var key in this) {
        document.write(key + ' : ' + coworkers[key] + "<br>");
    }
}    /*메소드 정의 중*/

coworkers.showAll();
  • 소속된 변수의 값으로 함수 지정 가능 -> 메소드 호출 가능
  • coworkers 대신 this 사용 가능

생활코딩 WEB2 JavaScript

반응형