반응형

Apply 함수


javascript 에서 함수는 일종의 객체인데 이때 apply 라는 내장함수를 포함하고 있어서 apply 함수를 사용 할 수 있음

함수를 apply  로 호출할때 첫번째 인자를 넘겨주게 되는데 이때 넘겨주는 인자는 함수 내에서 this 로 사용되어진다





apply 활용

1
2
3
4
5
6
7
8
9
10
11
12
function sum() {
    var s = 0;
    for (elem in this) { //this 에는 o1 의 내용이 들어 있게 되어 elem 에 하나씩 넘어가게 된다
 
    }
    
    console.log('1');
};
 
o1 = { v1: 10, v2: 20, v3: 30 };
sum.apply(o1); //javascript 에서는 일반 함수에 .apply 가 지원됨
 

 







좀 더 구체적인 예


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
function callMe(arg1, arg2) {
 
    var s = "";
    for (var elem in this) {
        s += this[elem] + ", " ;
    }
 
 
    s += "\n-------------\n";
 
    s += "\nthis value: " + this;
    s += "\n\n";
    s += "\n[[[arguments]]] : \n";
    for (i in callMe.arguments) {
        s += "arguments: " + callMe.arguments[i];
        s += "\n";
    }
 
    return s;
}
 
 
console.log("********************************\n");
 
console.log("Original function: ");
console.log(callMe(12));
 
console.log("\n======================== 1 =============================\n");
 
console.log("Function called with apply: \n");
 
//첫번째 인자는 this 로 사용될 개체 인자
//두번째는 인자는 함수로 넘어갈 인자 집합
 
console.log(callMe.apply(3, [45]));           //정수를 this 로 넘겨주는 형태임으로 for문에서 가져올게 없음
 
 
console.log("\n======================== 2 =============================\n");
 
console.log("객체를 this 로 넘긴다 보면: \n");
var arr = { v1: 10, v2: 20, v3: 30 };
console.log(callMe.apply(arr));
 

  





결과



위 실행에 대한 결과

첫번째 함수에 대한 호출이 callMe안의 this 가 원래의 this 에 관한 내용이 나옴으로 소스코드 형태로 출력결과를 스샷이 아닌 scripter 로 대신함


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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
위 소스코드에 대한 결과
 
Debugger listening on ws://127.0.0.1:22561/46f40b18-616e-4019-a9b5-ee13065adf13
For help see https://nodejs.org/en/docs/inspector
Debugger attached.
(node:10212) [DEP0062] DeprecationWarning: `node --inspect --debug-brk` is deprecated. Please use `node --inspect-brk` instead.
 
 
 
********************************
 
줄이 길어서 간격 조절을 함
//함수 자체 this 에 대한 내용
Original function:
[object Object], function () { [native code] }, function () { [native code] }, 
function () { [native code] }, 
function () { [native code] }, function () { [native code] }, function () { [native code] }, 
function () { [native code] }, function () { [native code] }, function () { [native code] }, 
function () { [native code] }, function () { [native code] }, function () { [native code] }, 
              [object global], [object process], 
 
function Buffer(arg, encodingOrOffset, length
{
  doFlaggedDeprecation();
  // Common case.
  if (typeof arg === 'number') {
    if (typeof encodingOrOffset === 'string') {
      throw new Error(
        'If encoding is specified then the first argument must be a string'
      );
    }
  ....
  ....
  ....
},
-------------
 
this value: [object global]
 
 
[[[arguments]]] :
arguments: 1
arguments: 2
 
 
======================== 1 =============================
 
Function called with apply:
 
 
-------------
 
this value: 3
 
 
[[[arguments]]] :
arguments: 4
arguments: 5
 
 
======================== 2 =============================
 
객체를 this 로 넘긴다 보면:
 
102030,
-------------
 
this value: [object Object]
 
 
[[[arguments]]] :
 
Waiting for the debugger to disconnect...
 
 
 
 






apply 메서드(Function)

 

함수를 호출하여 지정된 개체를 함수의 this 값으로 대체하고 지정된 배열을 함수의 인수로 대체합니다.

apply([thisObj[,argArray]])

thisObj

선택 사항입니다. this 개체로 사용될 개체입니다.

argArray

선택 사항입니다.함수에 전달될 인수 집합입니다.

argArray가 올바른 개체가 아니면 "개체가 필요합니다." 오류가 발생합니다.

argArray나 thisObj가 제공되지 않으면 원래 this 개체가 thisObj로 사용되고 인수는 전달되지 않습니다.

다음 코드에서는 apply 메서드를 사용하는 방법을 보여 줍니다

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
function callMe(arg1, arg2){
    var s = "";
 
    s += "this value: " + this;
    s += "<br />";
    for (i in callMe.arguments) {
        s += "arguments: " + callMe.arguments[i];
        s += "<br />";
    }
    return s;
}
 
document.write("Original function: <br/>");
document.write(callMe(12));
document.write("<br/>");
 
document.write("Function called with apply: <br/>");
document.write(callMe.apply(3, [ 45 ]));
 
// Output: 
// Original function: 
// this value: [object Window]
// arguments: 1
// arguments: 2
 
// Function called with apply: 
// this value: 3
// arguments: 4
// arguments: 5









반응형

+ Recent posts