본문 바로가기

IT/JavaScript

JavaScript #3 함수-2

4. 인수 배열 (arguments)
  - 함수를 호출할 때 전달된 모든 인수를 접근할 수 있게 한다.
    : 매개변수 개수보다 더 많이 전달된 인수도 포함한다.
[code javascript]
var print = function (log) {
    document.write (log);
    document.write ('<br>');
};

var sum = function () {
    var i, sum = 0;
    // arguments 는 length라는 속성은 있지만
    // 모든 배열이 가지고 있는 메소드가 있는 것은 아니다.
    // - 저자는 설계상의 문제로 지적했다.
    for (i = 0; i < arguments.length; i += 1) {
        sum += arguments[i];
    }
    return sum;
};
print (sum(4, 8, 15, 16, 23, 42)); // 108
[/code]

5. 반환
  - 함수는 항상 값을 반환한다.
    : 반환값이 없는 경우 undefined가 반환된다.
  - 함수를 new 라는 전치 연산자와 함께 실행하고 반환값이 객체가 아닌 경우
    반환값은 this (새로운 객체)가 된다.
    : 아래와 같이 생성자 호출 패턴에서 객체를 반환하도록 해보면
      new라고 하는 키워드의 의미가 사라진다. (8번째 라인)
[code javascript]
var myObject = function () {
    return {
        name : 'taegony',
        age : 10
    }
}();

var Quo = function (string) {
    this.status = string;
    return myObject;
};

Quo.prototype.get_status = function () {
    return this.status;
};

var myQuo = new Quo ('confused');
print (myQuo.age); // 10
print (myQuo.status); // undefined

if (myQuo === myObject) {
    print ('same');
}
else {
    print ('not same');
} // same (myQuo와 myObject는 같은 객체이다)
[/code]

6. 예외
  - throw문은 name, message 속성을 가진 예외 객체을 반환한다.
  - 예외 객체는 try 문의 catch 절에 전달된다.
  - try 문은 하나의 catch 블록을 가진다.
    : 따라서 catch 내에서 예외 객체의 name으로 종류를 구분해야한다.
[code javascript]
var add = function (a, b) {
    if (typeof a !== 'number' ||
       typeof b !== 'number') {
        throw {
            name : 'TypeError',
            message : 'add needs numbers'
        };
    }
    return a + b;
}

var try_it = function () {
    try {
        add ('seven');
    }
    catch (e) {
        print (e.name + ': ' + e.message);
    }
}

try_it (); // TypeError: add needs numbers
[/code]

7. 기본타입에 기능 추가하기
  - 자바스크립트는 기본타입에 기능 추가를 허용한다.
  - Object.prototype 또는 Function.prototype에 추가한다.
[code javascript]
// 모든 함수객체에 method라고하는 property를 추가한다.
// 내부에 정의된 property가 없으면 추가한다.
Function.prototype.method = function (name, func) {
    if (!this.prototype[name]) {
        this.prrototype[name] = func;
    }
};

Number.method ('integer', function () {
    return Math[this < 0 ? 'ceil' : 'floor'] (this);
});
print ((-10 / 3).integer()); // -3

String.method ('trim', function () {
    return this.replace (/^\s+|\s+$/g, '');
});
print ('"' + "    neat    ".trim () + '"'); // neat

// Number, String은 함수객체이다.
print (typeof String); // function
print (typeof Number); // function
[/code]

8. 재귀적 호출
  - 웹브라우져의 DOM(Document Object Model) 같은 트리 구조를 다루는데 효과적인다.
  - Tail reursion (꼬리 재귀) 최적화를 지원하지 않는다.
[code javascript]
<html>
<header>
<script language='javascript'>
var walk_the_DOM = function walk (node, func) {
    func (node);
    node = node.firstChild;
    while (node) {
        walk (node, func);
        node = node.nextSibling;
    }
}

// 인자 : attribute, value (value 는 optional)
var getElementsByAttribute = function (att, value) {
    var results = [];
    walk_the_DOM (document.body, function (node) {
        var actual = node.nodeType === 1 &&
                         node.getAttribute (att);
        if (typeof actual === 'string' &&
                    (actual === value ||
                     typeof value !== 'string')) {
            results.push (node);
        }
    });

    alert (results);
    // [object HTMLInputElement], [object HTMLInputElement]
};
</script>
</header>
<body onload="getElementsByAttribute ('value')">
    <input type='textbox' name='txt1' value='txt1Value'>
    <input type='button' name='btn1' value='btn1Value'>
</body>
</html>
[/code]

9. Scope
  - C언어 유형의 블록 scope를 제공하지 않는다.
  - 하지만 함수 scope는 제공한다.
    : 함수 내에서 정의된 매개변수와 변수는 함수 외부에서 유효하지 않다.
      함수 내에서 정의된 변수는 함수 어느 곳에서도 접근할 수 있다.
      : 내부 함수에서 자신을 정의한 외부함수의 매개변수와 변수에 접근할 수 있다.
        (closure 라고한다.)
  - 함수에서 사용하는 모든 변수는 가능하면 첫 부분에 선언하도록 한다.
[code javascript]
var foo = function () {
    var a = 3, b = 5;
    var bar = function () {
        var b = 7, c = 11; // a = 3, b = 7, c = 11
        a += b + c; // a = 21, b = 7, c = 11
    };
    bar ();
    // a = 21, b = 5, c = undefined
};
[/code]

공부한 책 : 자바스크립트 핵심가이드 - 더글라스 크락포드