Study JS for me/Keyword
Execution context 와 This
be well
2019. 4. 26. 19:24
Execution Context
(실행 컨텍스트)는 scope, hoisting, this, function, closure 등의 동작원리를 담고 있다.
어떤 함수가 호출되면 execution context가 만들어진다.
정의 : 실행컨텍스트는 추상적인 개념 . 실행 컨텍스트는 실행 가능한 코드가 실행되기 위해 필요한 환경
- 변수 : 전역변수, 지역변수, 매개변수, 객체의 프로퍼티
- 함수 선언
- 변수의 유효범위(Scope)
- this
this
자바스크립트에서 함수가 호출될 때, 함수 호출 방식에 따라 this 에 바인딩되는 객체가 달라진다.
정의 : 모든 함수 scope 내에서 자동으로 설정되는 특수한 식별자.
execution context의 구성요소 중 하나로 , 함수가 실행되는 동안 이용할 수 있다.
Binding Pattern | Binding Target |
Global 에서 this | window |
Function 에서 this | window |
Method 에서 this | 부모 object |
Construction mode 에서 this | (new연산자) 새로 생성된 객체 |
Call & Apply 에서 this | 첫 번째 인자로 명시된 객체 |
예제.
1. Global 에서 this
2. Function 에서 this
var global = 'this에게 호출될 예정'
console.log(this.global) // this에게 호출될 예정
function foo() {
console.log(this.global);
}
foo(); //this에게 호출된 예정
3. Method 에서 this
var count = function(){
val : 0,
increase : function() {
this.val += 1; //여기서 this는 부모객체인 count함수와 연결.
}
}
count.increase();
console.log(count.val) // 1
4. Construction mode 에서 this
function Foo(n) {
this.val = n;
}
var foo = new Foo('생성자함수');
//기존 함수에 new라는 연산자를 붙이면 생성자 함수가 만들어짐 기존함수와 혼란 방지를 위해 대문자로 쓰임
console.log(foo.val) // 생성자함수
var fee = Foo('실패'); //new 연산자가 없으면 생성자 함수로 동작하지 않음
console.log(fee.val)//undefined
5. Call & Apply 에서 this
fun.call(thisArg[, arg1[, arg2[, ...]]])
//thisArg :fun 호출에 제공되는 this의 값
//arg : 객체를 위한 인수
function foo() {
return this.length
}
foo.call([1,2,3]) // 3
fun.apply(thisArg, [argsArray])
//thisArg : 옵션. func 를 호출하는데 제공될 this 의 값
// [argsArray] : 옵션. func 이 호출되어야 하는 인수를 지정하는 유사 배열 객체,
function foo() {
return this.length
}
foo.apply([1,2,3]) // 3
fun.apply(thisArg, [1,2,3])
fun.call(thisArg, 1,2,3)