Execution context 실행 컨텍스트
함수가 호출되면 실행 컨텍스트 execution context가 만들어짐
call stack에 push
함수를 벗어나면 call stack에서 pop
scope 별로 생성
여기에 담긴 것
scope 내 변수 및 함수 (Local, Global)
전달 인자 (arguments)
호출된 근원 (caller)
this
'this' keyword
모든 함수 scope 내에서 자동으로 설정되는 특수한 식별자
execution context의 구성 요소 중 하나로, 함수가 실행되는 동안 이용할 수 있다
(this가 execution context라고 부르는 사람도 있음. 엄밀하게는 다름.)
this의 다섯가지 패턴 (암기!!)
1.Global: window
2.Function invocation호출: window //foo() 괄호 열고 괄호 닫고가 Function Invocation
3.Method 호출: 부모 object //객체에 담긴 함수가 Method다 eg. let obj = {foo: function() {console.log(this);}} //obj.foo() //method 호출 //여기서 this는 obj
let obj2 = {hello: {fn:function() {console.log(this);}}} //이 경우에 this는 hello 직계 부모만 가져온다.
4.Construction mode (new 연산자로 생성된 function 영역의 this): 새로 생성된 객체
constructor 인스턴스가 초기화될 때 실행하는 생성자 함수
eg.
function Car (brand, name, color) {
this.brand = brand;
this.name = name;
this.color = color;
}
let avante = new Car('hyndai', 'avante', 'black')
//avante 안에서 this는 avante다
call의 this 사용 예시
eg.
function identify() {
return this.name.toUpperCase();
}
function speak() {
var greeting = "Hello, I'm "+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); //Hello, I'm Reader
eg2.
function bar() {
console.log(this);
}
bar.call({a:1}) //{a:1} 그냥 넘겨주는 것
<call과 apply의 차이>
call은 ','로 넘겨주고 apply는 배열로 넘겨준다
eg.
var add = functon (x, y) {
this.val = x + y;
}
var obj = {
val: 0
};
add.apply(obj, [2,8]);
console.log(obj.val); //10
add.call(obj, 2, 8);
console.log(obj.val); //10
apply를 사용하는 경우
eg.
배열에 Math.max를 적용하고 싶은 경우
let arr=[10,3,5,15,23,1];
Math.max.apply(null, arr) //23