function f1() {
return this;
}
// 브라우저
f1(); // window객체: f1() === window;
function f2(){
"use strict"; // 엄격 모드 참고
return this;
}
f2(); // undefined
// 엄격모드가 function f2 밖에 위치해도 똑같이 undefined
var prop = 25;
var o = {
prop: 37,
func: function() {
return this.prop;
},
arrow: () => {
console.log(this.prop);
},
};
console.log(o.func()); // 37
console.log(o.arrow()); // 25
// arrow의 this는 window객체를 가르키고 있다.
// 전역스코프에 let / const로 선언하면 o.arrow()값은 undefined가 된다.
};
function
키워드는 해당객체를 바인딩하여 this
의 값 변경() => {}
은 상위 객체의 this를 받는다.function person(name, age, job) {
this.name = name;
this.age = age;
this.job = job;
}
// 생성자를 사용하지 않는 경우 : 단순 호출
let John = person('John', 20, student);
console.log(John); // undefined
// 생성자를 통한 객체 생성
let Vicky = person('Vicky', 32, Artist);
console.log(Vicky); // person {name: "Vicky", age: 32, job: Artist}
this
가 해당 객체에 바인딩 되어 해당 값을 읽는다.
일부 라이브러리에서 엘리먼트에 이벤트를 추가할 때, 콜백함수에서 this
를 사용하면 값이 바뀌는 경우가 있다.
this
는 이 3개를 이해하기 위한 발판이다.
this
를 자유자제로 바꿀 수 있는 메소드 :
call
함수와 유사하지만, 매개변수는 배열로 받는것에 있어 차이가 있다.const Jannie = {
name: 'Jannie',
age: 25,
gender: 'female',
};
function printProfile() {
console.log(this.name, this.age, this.gender);
}
let applying = printProfile.apply(Jannie);
// applying 값이 할당되지 않고 바로 출력된다 : applying === undefined
// Jannie 25 female
let calling = printProfile.call(Jannie);
// calling 값이 할당되지 않고 바로 출력된다. : calling === undefined
// Jannie 25 female
let binding = printProfile.bind(Jannie);
console.log(binding)
// ƒ printProfile() {
// console.log(this.name, this.age, this.gender);
// }
console.log(binding()) // Jannie 25 female
참조: