JavaScript

04_객체

보갱:) 2020. 10. 25. 13:51

04_객체.pdf
0.34MB

 


#js_object.html

 

    <button onclick="func1();">객체 생성 1</button>
    <br>
    <button onclick="func2();">객체 생성 2</button>
    <br>
    <button onclick="func3();">in/with</button>
    <br>
    <button onclick="func4();">객체 속성 추가/삭제</button>
    <br>
    <button onclick="func5();">객체 데이터 추가/출력</button>
    <br>
    <button onclick="func6();">객체 배열</button>
    <br>
    <button onclick="func7();">생성자사용</button>

 

 

객체는 관련된 데이터와 함수의 집합

일반적으로 여러 데이터와 함수로 이루어지는데, 객체 안에 있을 때는 보통 property(프로퍼티)와 method(메소드)라고 부름

 

 

객체 선언

var 변수명(객체명) = {

                        속성1(키값) : 값1,

                        속성2(키값) : 값2,

                        속성3(키값) : 값3

};

 

 

객체 내부 속성값 접근

1) 대괄호([])  -  변수명(객체명)[‘키값’];

2) 점(.)  -  변수명(객체명).키값;

 

 

객체 선언/호출

 객체는 키값을 사용하여 속성(멤버변수) 식별

 속성에 모든 자료형이 올 수 있으며, 그 중 함수 자료형인 요소를 메소드 라고 함

 객체 내에서 자신의 속성을 호출할 때 반드시 this키워드 사용

 객체의 모든 속성을 출력하기 위해서는 for in 문을 사용 → 일반 for문이나 while문으로는 전체 출력 불가

 


[객체 생성 1] 버튼 onclick="func1();"

    <script>
        function func1() {
            //testObj 객체 선언
            var testObj = {
                //속성1(키값) : 값1
                a: 100,
                //속성2(키값) : 값2
                b: 200
            };
            console.log(testObj);
            //객체 내부 속성값 접근방법(1) : 대괄호([])
            testObj['a'] = 300;
            //객체 내부 속성값 접근방법(2) : 점(.)
            testObj.b = 400;
            console.log(testObj);
        }
    </script>


[객체 생성 2] 버튼 onclick="func2();"

    <script>
        function func2() {
            //testObj 객체 선언
            //객체는 숫자, 문자열, 배열, 함수 등의 값을 가질 수 있다.
            var testObj = {
                a: 100,
                b: 200,
                //함수 자료형인 요소는 메소드라고 함
                c: function() {
                    alert("테스트");
                    return "하하하";
                }
            }
            console.log(testObj);
            //함수를 호출할 때는 ()사용
            console.log(testObj.c());
        }
    </script>


 

 

 

in / with

 in : 객체 내부에 해당 속성이 있는지 확인하는 키워드 (존재하면 true, 존재하지않으면 false)

 with : 코드를 줄여주는 키워드, 호출 시 객체명 생략 가능

 

in

속성명 in 변수명(객체명)

 

with

with(변수명(객체명)){ 속성명; 속성명; }


[in/with] 버튼 onclick="func3();"

    <script>
        function func3() {
            var testObj = {
                a: 100,
                b: 200
            };
            
            //in : 객체에 해당하는 속성이 있는지 검사 (있으면 true 없으면 false)
            console.log('a' in testObj);
            console.log('c' in testObj);
            
            //with : 코드를 줄여주는 키워드, 호출 시 객체명 생략 가능
            with(testObj) {
                a = 300;
                b = 400;
            }
            
            console.log(testObj);
        }
    </script>


 

 

객체 속성 추가 및 삭제

이미 생성된 객체에 추가적인 속성 및 메소드를 동적으로 추가 및 삭제  가능

 

추가

변수명(객체명).추가속성명=‘값’           //객체에 해당 속성이 있으면 true

 

삭제

delete(변수명(객체명).속성명);


[객체속성 추가/삭제] 버튼 onclick="func4();"

 

    <script>
            function func4() {
            var testObj = {
                a: 100,
                b: 200
            };
            console.log(testObj);

            //속성 추가 : 객체명.추가속성명=‘값’ 
            testObj.c = 300;
            console.log(testObj);
            
            //메소드 추가 : 객체명.추가속성명=‘값’ 
            testObj.d = function() {
                alert("객체 내부 함수입니다.")
            }
            testObj.d();
            console.log(testObj);

            //삭제 : delete(객체명.속성명);
            delete(testObj.a);
            console.log(testObj);
        }
    </script>

 


[객체데이터 추가/출력] 버튼 onclick="func5();"

    <script>
        function func5() {
            var name = prompt("이름입력");
            var age = prompt("나이입력");
            var addr = prompt("주소입력");
            var object = {
                //방법(1) : 객체(object)의 키값으로 출력
                //속성(키값) : 변수명
                name: name,
                age: age,
                addr: addr,
                
                //방법(2) : 객체(object)의 함수 리턴값으로 출력
                print: function() {
                    //객체 내에서 자신의 속성을 호출할 때: this키워드 사용
                    var str = 
                        "이름: " + this.name + "\n" +
                        "나이: " + this.age + "\n" +
                        "주소: " + this.addr;
                    return str;
                }
            }

            /* 방법(1)
            alert("이름: " + object.name + "\n" +
               "나이: " + object.age + "\n" +
               "주소: " + object.addr);
            */

            //방법(2)로 만든 객체 함수 호출
            alert(object.print());
            
            console.log(object);
        }
    </script>


 

 

 

 

객체 배열 활용

생성된 객체를 배열에 넣어 활용 가능

 

사용법

var 변수명 = new Array();

변수명.push({속성명:‘값’, 속성명:‘값’, 속성명:‘값’});

변수명.push({속성명:‘값’, 속성명:‘값’, 속성명:‘값’});

변수명.push({속성명:‘값’, 속성명:‘값’, 속성명:‘값’});


[객체 배열] 버튼 onclick="func6();"

    <script>
        function func6() {
            //[]; : 객체 배열 선언
            var objectArr = [];
            
            var test1 = {
                a: 100,
                b: 200
            };
            var test2 = {
                name: "홍길동",
                addr: "서울"
            };
            var test3 = {
                a: 300,
                b: 400
            };

            //배열에 값 추가
            objectArr.push(test1);
            objectArr.push(test2);
            objectArr.push(test3);
            console.log(objectArr);

            //(객체배열[인덱스].변수명)
            alert(objectArr[1].name);
        }
    </script>


 

 

 

생성자 함수

 this 키워드를 사용하여 속성을 생성하는 함수

 new라는 키워드를 사용하여 객체 생성

 생성자명의 첫 글자는 대문자로 시작

 

사용

function 생성자명(값1,값2,값3,…){

                                            this.속성 = 값1;

                                            this.속성 = 값2;

                                            this.속성 = 값3;

}


[생성자사용] 버튼 onclick="func7();"

    <script>
        //대문자로 시작하면 생성자 함수
        //test(); - 함수 / Test(); - 생성자함수
        function Student(name, age, address) {
            this.name = name;
            this.age = age;
            this.address = address;
        }

        function func7() {
            //생성자 함수 호출
            var s = new Student('홍길동', 20, '서울');
            console.log(s);
        }
    </script>

 

 

 

 

 

 

 

'JavaScript' 카테고리의 다른 글

05_BOM(1)  (0) 2020.10.25
04_객체(실습예제)  (0) 2020.10.25
03_함수(실습예제(2))  (0) 2020.10.22
03_함수(실습예제(1))  (0) 2020.10.22
03_함수(2)  (0) 2020.10.21