https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Operators/this
this - JavaScript | MDN
JavaScript에서 함수의 this 키워드는 다른 언어와 조금 다르게 동작합니다. 또한 엄격 모드와 비엄격 모드에서도 일부 차이가 있습니다.
developer.mozilla.org
this 란 ?
- 객체 자체를 가르키는 '참조변수( reference variable )' 혹은 '객체 참조( object reference )' 라고한다.
- 선언되거 호출된 위치에 객체를 참조하여, 늘 값이 바뀐다.
- 어느 객체가 호출 하고있냐에 따라 값이 달라진다.
- 함수가 만들어 질때가 아닌 '실행'될때 그 값이 정해진다.
1. 전역에서 불러온 경우
function a() {
console.log(this);
}
//a 가 제일 최상단 객체(전역 = window ) 에서 사용되었으므로 this 는 window 객체를 불러온다.
a();
전역에서 선언 되었으므로 window 객체가 반환된다.
2. 객체를 통해서 불러온 경우
//객체선언
let myObj ={
val1: 100,
func1: function(){
console.log(this);
}
}
//myObj 를 선언 한 객체에서 불러왔으니 myObj 객체를 불러온다
myObj.func1();
3.다른 곳에 따로 사용된 this를 다른 객체에서 불러올때
//전역에 값 선언
// let val = 300; 으로 선언하면 whatsYourValue(); 의 값은 undefined 가 된다.
var val = 300;
function whatsYourValue(){
console.log(this.val);
}
//객체선언
const penguin = {
val: 50,
//객체 안에서 함수를 불러내기위해 이와같이 작성
whatsYourValue: whatsYourValue,
}
const heejun ={
val: 100,
whatsYourValue: whatsYourValue,
}
whatsYourValue(); //300
penguin.whatsYourValue(); //50
heejun.whatsYourValue(); //100
더보기
전역에서 val을 let 이나 const 로 선언하면 whatsYoruValue() 는 undifinded 가 된다.
var 와 달리 let 과 const 는 블록 스코프(Block Scope) 로 전역에 선역이 되더라도,
전역 객체로는 선언하지 않기 때문에 undifinded 가 된다.
let 이나 const 로 선언된 전역 변수는 전역객체를 가르키는 this 로는 접근할수없다.
(이름으로는 접근이 가능하다)
var 와 달리 let 과 const 는 블록 스코프(Block Scope) 로 전역에 선역이 되더라도,
전역 객체로는 선언하지 않기 때문에 undifinded 가 된다.
let 이나 const 로 선언된 전역 변수는 전역객체를 가르키는 this 로는 접근할수없다.
(이름으로는 접근이 가능하다)
4. 객체 자신에게서 this를 쓸때
const bank = [
{
name:'펭귄은행',
account: 100,
vipAccount: 6,
allAccount: function allAccount(){
console.log(`${this.name} 계좌 수 : ${this.account + this.vipAccount}`);
//펭귄 은행 계좌수 106
}
},
{
name:'남극은행',
account: 200,
vipAccount: 4,
allAccount: function allAccount(){
console.log(`${this.name} 계좌 수 : ${this.account + this.vipAccount}`);
//남극은행 계좌수 204
}
},
{
name:'추워은행',
account: 800,
vipAccount: 5,
allAccount: function allAccount(){
console.log(`${this.name} 계좌 수 : ${this.account + this.vipAccount}`);
//추워은행 계좌수 805
}
}]
bank[0].allAccount(); //펭귄 은행 계좌수 106
bank[1].allAccount(); //남극은행 계좌수 204
bank[2].allAccount(); //추워은행 계좌수 805
'FrontEnd > Vanilla JS' 카테고리의 다른 글
[JS] 포켓몬 API활용하기 (0) | 2024.03.14 |
---|---|
[JS] 과제 준비하기 (0) | 2024.03.13 |
[JS]객체지향 프로그래밍 과 생성자 (0) | 2024.03.05 |
[JS] 클로저 - closures (0) | 2024.03.05 |
[JS] 배열에 쓸수있는 여러 함수들 (0) | 2024.03.04 |