#30 자바스크립트에서 this 사용하기

2023. 7. 20. 17:46자바스크립트

반응형

this는 사전적 의미는 이것이지만 자바스크립트에서는 누가 나를 호출했느냐란

의미로 this가 어떻게 쓰여 졌느냐에 따라 달라진다는 것 입니다.

 

 

 

1. this를 단독으로 사용할 경우

 

  // this를 단독 호출하는 경우 global object를 가리킵니다.

  var x = this;
  document.write(x); // 결과 : [object Window]

 

 

 

2. this를 함수 안에서 사용할 경우

 

 //  ===== 함수의 주인인 [object Window] 에게 바인딩이 됩니다. =====

 function myFun() {
   return this;
 }
 document.write(myFun());  // 결과 : [object Window]

 

 

 // ===== addNum() 함수에서 this.num을 선언하여 실행한 예 ===== 

 

 var num = 0;  // num 전연변수 선언 
  
 function addNum() {
   this.num = 10;
   num++;
 }
  
 addNum();  // addNum 함수 실행
  
 document.write(num);  //num 값 출력됨 : 11

 

 

 

3. this를 메서드 안에서 사용할 경우

 

// 아래 예제를 보면 num_Sum 메서드를 함수로 선언하여  그 안에서 this를 사용한 예시이다.

 

var n_s = {
  num1: 1,
  num2: 2,
  num_Sum: function () {
    return this.num1 + this.num2;
  }
};

document.write(n_s.num_Sum());  // 출력 : 3

 

 

4. this를 이밴트 핸들러에서 사용할 경우

 

// 여기서 this는 이벤트를 받는 HTML 요소를 가리킵니다.

 

<input type="button" id="btn" value="버튼을 눌러봐!" 

<script>  
var btn = document.querySelector('#btn');   
btn.addEventListener('click'function () {
  alert(this); 
});
</script>

 

◆ 아래 버튼을 누르면...

 아래와 같이 메시지가 뜹니다. 여기서 this는  Input에서 click 이밴트가 발생된 HTML Input 요소를 가리킵니다.

 

 

5.  this를 생성자(new)에 사용할 경우

 

function Person(name) {
  this.name = name;
}
 
var a = new Person('홍길동');
var b = new Person('박철수');
  
document.write(a.name+"</br>"); 
document.write(b.name);  

 

//  출력결과

//  홍길동

//  박철수

 

 

6. this를 명시적 바인딩으로 사용

 

function whoisThis() {
  document.write(this);
}
whoisThis();  //출력 결과 : object Window
  
document.write("</br>");  
  
var obj = {x: 123};  

whoisThis.call(obj);  //출력 결과 : object Object 

 

// 참고사항 : call()은 인수 목록을 받고 apply()는 인수 배열을 받음.

 

 

7. this를 화살표(=>) 함수 사용

화살표 함수는 ES6문법입니다. function 키워드 사용해서 함수를 만든 것보다 간단히 함수를 표현할 수 있습니다. 

즉, 화살표 함수는 javascript에서 함수를 정의하는 function 키워드 없이 함수를 만들 수 있으며, return 키워드 없이, 식을 계산한 값이 자동으로 반환됩니다. () 안에 함수의 인자가 들어가고, => 오른쪽에는 결과를 반환하는 식입니다. 

 

var Person = function (name, age) {
  this.name = name;
  this.age = age;

 

 

 this.say_not = function () {
  setTimeout(function(){
  document.write("======화살표 함수 사용안한거 예)======</br>");
  document.write(this+"</br>"); // [object Window]
  document.write('이름 : ' + this.name + '</br>나이 : ' this.age + "</br></br>");
   }, 100);
  };

 

   // 위 코드를 보면 내부 함수에서 this가 전역 객체 [object Window] 를 가리겨서 엉뚱한

   결과가 나오기에 아래와 같이 화살표(=>) 함수를 사용하면 올바른 결과를 얻을 수 있다.

   
 this.say_good = function () {
  setTimeout(()=>{
  document.write("======화살표 함수 사용 예)=====</br>");
  document.write(this+"</br>"); // [object Object]
  document.write('이름 : ' + this.name + '</br>나이 : ' + this.age);
   }, 100);
  };


};
var me = new Person('홍길동', 28);
 
me.say_not();  //화살표 함수를 사용안한거 출력
me.say_good(); //화살표 함수를 사용한거 출력

 

 

출력 결과 캡처

 

 

◆화살표 함수에 대한 추가 예)

 

//ES5문법 일반 함수 사용 예)  
function myFunc(name) {
  return "①일반 함수 : 안녕? " + name;
}
document.write(myFunc("철수")); 
  
document.write("</br>");   
  
  
//ES6문법 화살표 함수 사용 예)  
const myFunc2 = (name) => {
  return `②화살표 함수 : 안녕? ${name}`;
};
document.write(myFunc2("철수"));
  
document.write("</br>");  
  
  
//ES6문법 화살표 함수 사용 예2)  
const myFunc3 = (name) => `③화살표 함수[{},return 생략] : 안녕? ${name}`;
document.write(myFunc3("영희"));  

 

 

출력결과  

 

 

 

※ 혹시 설명에 오류가 있다면 양해 부탁드립니다.

 

 

반응형