javascript에서 this는 다른 언어에서와 다르게 어디서든 사용할 수 있음. 함수와 객체(메서드)의 구분이 느슨하지만 this를 통해 구분할 수 있음.
this는 기본적으로 함수를 호출할 때 결정됨
console.log(this) //window {...}
전역공간에서 this를 호출하면 window객체를 뜻함.
자바스크립트 전역공간에서 변수를 선언하면 window객체에 (nodejs환경에선 global) 해당 변수를 할당함.
let func = function(x) { console.log(this, x); } func(1); // window {...} let obj = { method : func }; obj.method(2); // {method : f} obj['method'](2); // {method :f}
메서드에서 this를 호출하면 해당 메서드가 나옴.
그리고 객체를 호출하는것이기 때문에 obj['method']처럼 해도 가능함.
let obj = { outer : function() { console.log(this); // 1 let innerFunc = function(){ console.log(this); // 2, 3 } innerfunc() let obj2 = { innerMethod : innerFunc }; obj.innerMethod(); } }; obj1.outer()
1번 console.log는 obj1.outer 함수가 호출될때 outer앞에 . 이 있기 때문에 메서드로서 호출된 것이라서 obj1 호출.
2번 console.log는 innerfunc()에 의해서 호출되는데 . 이 없기 때문에 함수로서 호출된것이라서 window 호출.
3번 console.log는 obj.innerMethod()에 의해 호출되는데 . 이 있기 때문에 메서드로서 호출된것이라서 obj2호출
let obj = { outer : function() { console.log(this); // 1 let innerFunc = function(){ console.log(this); // 2 } innerfunc() let self = this; // 추가! let innerFunc2 = function() { console.log(self); // 3 } }; obj1.outer()
//1은 obj, //2는 window // 3은 obj
let obj = { outer: function(){ console.log(this); let innerFunc = () => { console.log(this); }; innerFunc(); } }; obj.outer()
이렇게 화살표 함수로 사용하게되면 console.log 둘다 {outer: f}를 바라보게됨.