[코드잇 풀스택 1기] - Javascript _ this
2024. 7. 10. 20:20ㆍ취업 준비 !
Javascript에서 this는
객체 지향 프로그래밍에서 객체의 문맥을 나타내는 데 사용됩니다.
전역 문맥
console.log(this);
// 브라우저는 windows 객체를 가르키고있고 있습니다.
객체 메서드
const minsu{
name = "minsu"
age = 19
greet: function(){
console.log(this.name); // this는 minsu라는 객체를 가리키고있습니다.
}
}
minsu.greet(); // 출력을 하면 minsu를 출력합니다.
생성자 함수
function Person(name){
this.name = name;
}
const person_1 = new Person('minsu');
console.log(person_1); //파라미터로 받은 name을 그대로 this로 가지고 오는 방식입니다
함수 호출
function showThis(){
console.log(this);
}
sohThis();
// 엄경모드 : undefined
// 비엄격 모드 : window
call, apply, bind 메서드
function introduce(){
console.log('My name is ${this.name}');
}
const person = { name : 'minsu'};
introduce.call(person); // 출력 My name is minsu
introduce.apply(person); // 출력 : My name is minsu
const boundIntroduce = introduce.bind(person);
boundIntroduce(); // 출력 : My name is minsu
화살표 함수 (Arrow Function)
const minsu = {
name = 'minsu'
greet: function(){
const innerFunc = () => {
console.log(this.name);
};
innerFunc();
}
};
name.greet(); // 출력 : minsu
위 설명 예제처럼
this는 함수 호출 방식에 따라 달라지고
객체 메서드 내에서는 그 객체를 가키키고 있습니다.
전역 문맥에서는 전역 객체를 가르키고.
this를 사용하기 위해서는 문맥에 따라 다르게 동작하기 때문에 이해를 잘 하셔야합니다.
'취업 준비 !' 카테고리의 다른 글
[코드잇 풀스택 1기] - React 렌더링 방식 (0) | 2024.07.20 |
---|---|
[코드잇 풀스택 1기] - 렉시컬 스코프(Lexical Scope) (0) | 2024.07.10 |
[코드잇 풀스택 1기] - var, let, const 비교 (1) | 2024.07.09 |
[코드잇 풀스택 1기] - 브라우저 동작원리 (1) | 2024.07.05 |
[코드잇 풀스택 1기] - 시맨틱 태그 (0) | 2024.06.24 |