[코드잇 풀스택 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를 사용하기 위해서는 문맥에 따라 다르게 동작하기 때문에 이해를 잘 하셔야합니다.