javascript에서 상황 별 this 가 바라보는 객체는 아래와 같다

 

1. 함수 자체로써 호출되었을 때 : 브라우저 환경 - window / node js 환경 - global

2. Method로써 호출되었을 때 : 호출 주체 (객체)

// 함수 자체로써 호출되었을 때 - node js 환경

let example_func = function(x, y, z){
	console.log(this, x, y, z);
	}

example_func(1, 2, 3); // output : global(실제 출력된 내용은 너무 길게 나옴), 1, 2, 3

// Method로써 호출되었을 때

let example_func_2 =  {
		name: "chunws",
	        ex_method: function (x, y, z){console.log(this, x, y, z);}
            }

example_func_2.ex_method(1, 2, 3); // output : example_func_2(객체 내용), 1, 2, 3

 

이렇듯, javascript 에서의 this 는 상황에 따라 다른 객체를 바라보고 있지만

특정 객체를 바라보도록 설정할 수 있는데, 이것을 binding 이라고 한다.

 

실행 방법은 [기존 함수 이름].call() 또는 [기존 함수 이름].apply() 로 표현할 수 있는데,

call 과 apply 의 method 는 1. 이름과 2.변수를 넣을 때 형식이 다르다는 것을 제외하면 기능적으로는 완전히 같다

 

// call 을 통한 this binding

let example = function(x, y, z) {
	console.log(this, x, y, z);
    }
    
example.call({name : "chunws"}, 1, 2, 3); // output: {name:"chunws"}, 1, 2, 3


//apply 를 통한 this binding

let example_2 = {
	name : "something else",
    ex_function : function(x, y, z){
    	console.log(this, x, y, z) ;
        }
    }
        
example_2.exfunction.apply({name : "chunws"}, [1, 2, 3]) // output : {name:"chunws"}, 1, 2, 3

 

call 을 통한 binding은 기존과 같이 변수를 넣어주면 되는 반면,

apply 를 통한 binding은 [ ] 안 쪽으로 변수를 넣어서 binding을 진행한다.