본문 바로가기

Programing/JavaScript

[JavaScript] this / call, apply 호출


What happens if I call the function?

- Local memory 생성

    - lexical scope 의존

- Local execution context 생성



Execution context (ㅠ)

- 어떤 함수가 호출되면, 실행 컨텍스트 execution context가 만들어진다

    - call stack에 push,

    - 함수를 벗어나면 call stack에서 pop

- scope 별로 생성

- 여기에 담긴 것

    - scope 내 변수 및 함수 (Local, Global)

    - 전달 인자 (arguments)

    - 호출된 근원 (caller)

    - this 




'this' keyword

- 모든 함수 scope 내에서 자동으로 설정되는 특수한 식별자

- execution context의 구성요소 중 하나로, 함수가 실행되는 동안 이용할 수 있다.




5 Patterns of Binding 'this'

1. Global : window

2. Function 호출 : window

3. Method 호출 : 부모 object

4. Construction mode (new 연산자로 생성된 function 영역의 this) : 새로 생성된 객체

5. .call or .apply 호출 : call, apply의 첫번째 인자로 명시 된 객체




1. Global : window

window는 전역객체이다. 


1
2
3
var test = '123';
test === window.test  // true
test === this.test  // true
cs



2. Function 호출 : window

1
2
3
4
5
6
7
8
var name = 'Global Variable';
console.log(this.name);  // 'Global Variable'
 
function foo() {
    console.log(this.name);  // 'Global Variable'
}
 
foo();
cs


1
2
3
4
5
6
7
8
9
10
11
var name =  'Global Variable';
 
function outer() {
    function inner() {
        console.log(this.name);  // 'Global Variable' (this는 window)
    }
 
    inner();
}
 
outer();
cs


1
2
3
4
5
6
7
8
9
10
var name = 'Global Variable';
 
function outer2() {
    var closure = function() {
        console.log(this. name);  // 'Global Variable' (this는 window)
    }
    return closure;
}
 
outer2()();
cs



3. Method 호출 : 부모 object

객체안에서 불리는 function은 method다!!


1
2
3
4
5
6
7
8
9
10
11
var counter = {
    var0,
    increment : function() {   // increment는 method
        this.val += 1;   // 여기서 this는 counter
    }
};
 
counter.increment();  // method 인보케이션
console.log(counter.val);  // 1
counter['increment']();
console.log(couter.val);  // 2
cs


1
2
3
4
5
6
7
8
9
10
11
var obj = {
    fn: function(a, b) {
        return this;
    }
};
var obj2 = {
    method: obj.fn
};
 
console.log(obj2.method() === obj2);  // true 앞에꺼랑 같아서  true로 나온거임
console.log(obj.fn() ===  obj);  // true   (obj === obj 이기 때문에)
cs



4. Construction mode (new 연산자로 생성된 function 영역의 this) : 새로 생성된 객체

1
2
3
4
5
6
7
8
9
10
11
12
13
14
function Car(brand, name, color) {
    this.brand = brand;
    this.name = name;
    this.color = color;
}
 
var avante = new Car('현대''아반떼''gray');
(avante = 인스턴스 instance)
 
avante.brand  // '현대'
 
var bmw = new Car('BMW''520d''yellow');
 
bmw.name  // '520d'
cs



5. .call or .apply 호출 : call, apply의 첫번째 인자로 명시 된 객체

1
2
3
4
5
6
7
8
function add(x, y) {
    console.log(this);
    return x + y;
}
 
add(45);  // 9
add.call(null45);  // 9
add.apply(null, [45]);  // 9 (인자를 배열로 입력)
cs


add.call(null, 4, 5); << null위치에 어떤값을 입력함에 따라 this가 달라진다


예제


1
2
3
4
5
6
7
8
9
10
11
12
13
14
function identify() {
    return this.name.toUpperCase();
}
function speak() {
    var greeting = 'Hello, I'' + identify.call(this);
    console.log(greeting);
}
var me = { name : 'Kyle' };
var you = { name : 'Reader' };
identify.call(me);  // KYLE
identify.call(you);  // READER
speak.call(me);  // Hello, I'm KYLE
speak.call(you);  
cs


→ this를 명시적으로 넣어주기


1
2
3
4
5
6
7
8
function foo() {
    console.log(this)
}
 
foo();   // window
// foo는 window.foo이기 때문에 this는 부모를 찾는 것임으로,
// this는 window다.
 
cs













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

[JavaScript] hasOwnProperty()  (0) 2019.02.27
[JavaScript] Function Methods, Prototype  (0) 2019.02.14
[JavaScript] Closure  (0) 2019.02.13
[JavaScript] Scope  (0) 2019.02.13
[JavaScript] for문, forEach(), for in, for of 차이  (0) 2019.02.12