this는 함수 실행시 호출 방법에 의해 결정되는 특별한 객체.
함수 실행시 결정되므로, 실행되는 맥락(execution context)에 따라 this가 결정된다.
이해하기 어려우니 중요한 포인트를 짚어가며 하나씩 확인해 본다.
//webbrowser
console.log(this)
//Window {0: global, 1: global, window: Window, self: Window, document: document, name: "", location: Location, …}sf
window 객체는 browser의 요소들과 자바스크립트 엔진, 그리고 모든 변수를 담고있는 객체이다.
참고: https://www.zerocho.com/category/JavaScript/post/573b321aa54b5e8427432946
사용을 권장하지 않는 방법이며, function호출시 this를 사용 할 이유가 없다.
console.log(this); //window
function func(){
return console.log(this);
};
func();//window
함수 표현식으로 함수를 만들고, 객체 프로퍼티 caller 함수를 할당 할 경우 해당 함수는 method라고 합니다.
아래 코드에서 동일한점은 method를 호출 한다는 점입니다.
따라서 this는 해당 객체가 가지고있는 property에 접근합니다.
//method 호출
let testText = {
text : 'method 호출 시',
caller : function(){
console.log(this.text);
}
}
testText.caller();
//"method 호출 시"
//new 생성자 호출
class Test{
value = 'new 생성자 호출시'
getValue(){
return this.value;
}
}
let test = new Test();
test.getValue();
//"new 생성자 호출시"
주어진 this값 및 각각 전달된 인자와 함ㅋ께 함수를 호출한다.
!!코드분석!!
new Food('cheese', 5).name
(new 생성자로 인스턴트 화 시키는데 인자를 'chease' , 5를 입력한다.)
Product.call(this, name, price)
(전달받은 인자로 Product class를 호출한다)
Product class 에서 this.name, this.price의 property에 전달받은 인자를 할당한다.
최종적으로 Product class의 property에는 name = 'cheese', price = 5가 할당되어 있기 때문에 new Food('cheese', 5).name의 마지막 .name의 변수로 console.log가 가능해진다.
//Product클래스
function Product(name, price) {
this.name = name;
this.price = price;
}
//Food클래스
function Food(name, price) {
Product.call(this, name, price);
this.category = 'food';
}
console.log(new Food('cheese', 5).name);
// expected output: "cheese"
참고 : https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Function/call
call()과 유사하나 인자들의 단일 배열을 받는다는 점이 차이점이다.
const numbers = [5, 6, 2, 3, 7];
const max = Math.max.apply(null, numbers);
console.log(max);
// expected output: 7
const min = Math.min.apply(null, numbers);
console.log(min);
// expected output: 2
참고: https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Function/apply
call 과 유사하게 this 및 인자를 바인딩하나, 당장 실행하는 것이 아닌 바인딩된 함수를 리턴하는 함수이다.
bind()의 주요목적은 함수와 객체를 서로 묶는것이다.
function greet(){
return this.jhon;
}
let person = {jhon : '안녕하세요'}
//greet 함수와 person의 객체를 연결해서 최종적으로 해당 함수의 this를
//person 객체가 될 수 있도록 한다.
let greeting = greet.bind(person);
console.log(greeting());
//결과 안녕하세요
//sum 함수 호출 시 a = 5
function sum(a, b){
return a + b;
}
let add = sum.bind(null , 5)
console.log(add(10));
//결과 15