함수(Function)

2016. 11. 23. 00:00Programming/JavaScript

**생활코딩:함수지향~클로저까지 복습할 것**


<오늘 배운 것>


1) function의 특징: 자유로움(데이터 타입, return값, 형태 등)

객체로도 되고 값으로도 사용될 수 있다.


<함수의 배열을 만들어 사용하는 모습>

1
2
3
4
5
6
7
8
9
function cal(mode){
    var funcs = {
        'add' : function(a, b){return a + b},
        'subtract' : function(a, b){return a - b}
    }
    return funcs[mode];
}
alert(cal('add')(2,1));
alert(cal('subtract')(2,1));   
cs


<argument 자리에 바로 배열 넣어 사용 가능>

1
2
3
4
5
6
7
8
9
function sum(){
    var i, _sum = 0;
    //arguments.length(배열 길이)
    for(i = 0; i < arguments.length; i++){
        document.write(i+' : '+arguments[i]+'<br/>');
        _sum += arguments[i];
    }   
    return _sum;
}
document.write('result : ' + sum(1,2,3,4));
cs


<apply 사용해 sum 함수 호출하기>

** this는 함수가 소속된 객체 의미(따라서 o1이 될 수도, o2가 될 수도 있다)

*** sum.apply(o1)를 실행하면 this가 o1으로 바뀐다.


1
2
3
4
5
6
7
8
9
10
11
o1 = {val1:1, val2:2, val3:3}
o2 = {v1:10, v2:50, v3:100, v4:25}
function sum(){
    var _sum = 0;
    for(name in this){
        _sum += this[name];
    }
    return _sum;
}
alert(sum.apply(o1)) // 6
alert(sum.apply(o2)) // 185
cs


2) function 정의, 사용법


<함수는 일종의 클래스, new로 객체 생성해 사용>

** this.introduce = function()에서 함수는 메소드 역할


1
2
3
4
5
6
7
8
9
10
11
function Person(name){
    this.name = name;
    this.introduce = function(){
        return 'My name is '+this.name
    }   
}
var p1 = new Person('egoing');
document.write(p1.introduce()+"<br />");
 
var p2 = new Person('leezche');
document.write(p2.introduce());
cs


<응용: 브라우저에서>


//정의
var counter = function(){
    this.count += 1;
    document.getElementById("count").innerHTML = this.count;
}
//사용
<button onclick="counter()">count</button>
<h1 id="count"></h1>



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>JavaScript function</title>
</head>
<body>
<h1>함수를 정의하고 사용해보자</h1>
 
<script>
function sum(a,b){
    //return되는 값, 매개변수의 데이터 타입이 없다.
    return a+b;
}
document.write("<h3>sum(10,20): "+sum(10,20)+"</h3>");//30출력
 
var sumVal = function(a,b){
    return a+b;
}//이처럼 변수에 담아 사용하는 경우 더 속도가 빠르다.
document.write("<h3>sumVal(10,20): "+sumVal(10,20)+"</h3>");
 
//b 값이 undefined일 때도 출력되게끔
var multiply = function(a,b){
    if(b===undefined){b=1;}
    return a*b;
}
document.write("<h3>multiply(7): "+multiply(7)+"</h3>");//7출력
 
//더 간결한 방식
var multiply2 = function(a,b=1){
    return a*b;
}
document.write("<h3>multiply(7): "+multiply2(7)+"</h3>");//7출력
document.write("<h3>multiply(7,7): "+multiply2(7,7)+"</h3>");//7출력
 
var count = 0//전역변수
var counter = function(){
    this.count += 1;
    document.getElementById("count").innerHTML = this.count;
}
 
var count2 = 0//전역변수
var counter2 = function(){ //함수 in 함수도 가능
    function add(){
        count2+=1;
        }
    add();
    document.getElementById("count2").innerHTML = this.count2;
}
 
</script>
<button onclick="counter()">count</button>
<h1 id="count"></h1>
<hr>
<button onclick="counter2()">count2</button>
<h1 id="count2"></h1>
</body>
</html>
cs


'Programming > JavaScript' 카테고리의 다른 글

상속(prototype)  (0) 2016.11.27
AJAX 정리  (0) 2016.11.23
JSON 정리  (0) 2016.11.23
문자열, 배열 처리  (0) 2016.11.22
자바스크립트 소개  (0) 2016.11.22