기본적으로 전역컨텍스트에서 this는 window를 가리킨다.
const name = "elice";
console.log(this); //window {...}
일반함수 안에서 name을 정의해놓고 this.name으로 접근하려고 한다면 불가능하다. this는 window를 가리키기 때문이다.
function myFunc() {
const name = "elice";
console.log(this);
}
myFunc(); // 일반 함수 호출시 window {...}
1. 객체의 메서드 호출 시 this값은 객체를 가리키게 된다.
const person2 = {
name: 'min',
study : function() {
console.log(`${this.name}이는 js를 공부하고 있습니다.`)
console.log(this)
}
}
person2.study();
2. bind
this를 동적으로 묶어준다.
function Person(name){
this.name = name;
this.printName = function(){
console.log(this.name)
}
}
const p = new Person('Daniel')
p.printName.bind(p)();
3. 화살표함수의 경우, 메서드라 할지라도 해당 객체를 가리키지 않는다.
let o = {
name: 'Daniel',
f1: ()=>{
console.log("[f1] this :", this);
},
f2: function(){
console.log("[f2] this :", this);
},
}
o.f1(); // global
o.f2(); // o
근데 또 setTimeout의 콜백으로 넘기면 둘다 global이 된다.
let o = {
name: 'Daniel',
f1: ()=>{
console.log("[f1] this :", this);
},
f2: function(){
console.log("[f2] this :", this);
},
}
setTimeout(o.f1,3000);
setTimeout(o.f2,6000);
둘다 global이 됨! 하나는 화살표함수는 undefined가 되고 일반함수는 setTimeout객체 그 자체를 가리키게 된다.
그래서 바인딩을 시켜주어야 한다.
let o = {
name: 'Daniel',
f1: ()=>{
console.log("[f1] this :", this);
},
f2: function(){
console.log("[f2] this :", this);
},
}
setTimeout(o.f1.bind(o),3000); //undefined
setTimeout(o.f2.bind(o),3000); //o를 가리킴
4. 생성자함수 호출의 경우
함수를 객체로 생성하는 경우 this가 생성하는 함수 내부를 가리킨다.
function myFunc(name) {
this.name = name;
this.getName = function () {
console.log("getName this:", this);
return this.name;
};
console.log("myFunc this:", this);
// return this; 생략 가능합니다.
}
const o = new myFunc("elice"); // myFunc this: myFunc {...}
o.getName() // myFunc this: myFunc {...}
하지만 객체 안 함수의 내부 함수에 This는 또 전역객체를 가리킨다
const o = {
name: "elice",
myFunc: function () {
return function () { console.log(this) }
},
};
o.myFunc()(); // window {...}
5. 화살표함수와 일반함수의 this 차이를 살펴보자
화살표 함수의 this : 호출된 함수를 둘러싼 실행 컨텍스트
일반 함수의 this: 새롭게 생성된 실행 컨텍스트
const o = {
method(){
console.log('context: ', this )
let f1 = function(){
console.log('[f1] this: ', this)
}
let f2 = () => {
console.log('[f2] this :', this)
}
f1() // undefined
f2() // o를 가리킴
},
};
o.method()
예제)
window.name = "Daniel"
let o ={ name : "Kim"}
let arrowFunction = (prefix) => console.log(this)
function serrowFunction(prefix){
console.log(this)
}
arrowFunction("Dr.") //window를 가리킴
serrowFunction("Dr. ") //window를 가리킴
이 문제를 보자.
const BankAccount = {
deposit: 0,
name: '',
changeName: function (name) {
// BankAccount의 이름을 바꾸세요.
this.name = name;
return;
},
saveMoney: function (amount) {
// amount를 deposit에 더합니다.
this.deposit += amount;
return;
},
withdrawMoney: function (amount) {
// amount를 deposit에서 뺍니다.
this.deposit -= amount;
return;
},
getDeposit: function () {
// deposit을 리턴합니다.
return this.deposit;
},
};
export default BankAccount;
메서드에서 function에서 this를 사용하는 경우 해당 객체를 가리키므로 this에서 변수값을 가져올 수 있는 것이다.
'Javascript' 카테고리의 다른 글
함수 내보내기, 가져오기 관련 (0) | 2022.10.19 |
---|---|
closure 클로저 (0) | 2022.10.18 |
HTTP request, response, CSR, SSR, FETCH API (1) | 2022.10.11 |
Map에 대하여 (0) | 2022.10.07 |
set에 대하여 (0) | 2022.10.07 |