GOhACK/웹

[JavaScript JQuery] 6장 객체

LinZBe4hia 2016. 12. 28. 00:13

6.2 속성과 메서드

배열 내부에 있는 값: 요소(element)

객체 내부에 있는 값: 속성(property)


코드 6-5 객체의 속성이 가질 수 있는 자료형

var object = {
    number: 273,
    string: 'RintLanTta',
    boolean: true,
    array: [52, 34, 66,21],
    method: function() {

    }
};


javascript는 this 키워드를 생략할 수 없다.

코드 6-7

<script>
    var person = {
        name: '윤인성',
        eat: function(food) {
            alert(this.name + ''+ food + '을/를 먹습니다.');
        }
    };

    // call method
    person.eat('');
</script>


6.4 객체 관련 키워드


6.4.2 with 키워드

만약 with 키워드를 사용하는 객체의 속성(property)와 외부 변수 이름이 같으면 충돌이 발생한다.

이 경우 JavaScript는 객체의 속성(property)를 우선시한다.

코드 6-13

<script>
    // declare a variable
    var student = {
        이름: '연하진',
        국어: 92, 수학: 98,
        영어: 96, 과학: 98,
        output: '이미 있당!'
    };

    // display
    var output = 'gg';
    with (student) {
        output += '이름: ' + 이름 + '\n';
        output += '국어: ' + 국어 + '\n';
        output += '총점: ' + (국어 + 수학 + 영어 + 과학);
    }

    alert(output);
</script>


with(student)문 안에서는 output이 식별자 student 안의 output을 생각하는 것이고, 

alert(output)은 외부 변수를 사용하기 때문에 경고창에는 gg가 출력된다.



코드 6-14 with 키워드를 사용 시 변수 이름 충돌 해결 방법

    // display
    var output = '';
    with (student) {
        window.output += '이름: ' + 이름 + '\n';
        window.output += '국어: ' + 국어 + '\n';
        window.output += '총점: ' + (국어 + 수학 + 영어 + 과학);
    }

    alert(output);



6.7 함수를 사용한 객체 생성