javascript

54.this이해

life... 2022. 4. 13. 21:31

this는 전역에서,함수에서 사용 가능하다.

함수에서도 객체안의 메소드,생성자함수, 특정 계산 목적의 용도에 따라 this가 다르게 해석된다.

 

1.

 

this.valueA = 'a';
console.log(valueA);  //a
valueB = 'b';
console.log(this.valueB); //b

//아무것도 없는 공간이 브라우저 환경이고 이 공간에서 this가 윈도우를 가리키므로

//window.valueA='a'라는 의미이다.

 

2.

 

function checkThis() {
  console.log(this);
}

checkThis();

 

//일반적 함수에선 this는 window를 가르킨다.

 

3.

function checkThis2() {
  "use strict";
  console.log(this);
}

checkThis2();

//일반적 함수안에 엄격한 모드"use strict";

//를 넣어주면 this는 undefined가 된다.

 

4.

//Product함수처럼 생성자함수로 작성되었을 때

//이면서

//new를 사용하지 않은 경우

 

function Product(name, price) {
  this.name = name;
  this.price = price;
}
const product1 = Product('가방', 2000);
console.log(window.name);
console.log(window.price);

 

//this는 윈도우를 가리킨다.

//따라서 window.name을 or this.name을 하면 동일하게 출력된다.

 

5.

 

const product2 = {
  name: '가방2',
  price: 3000,
  getVAT() {
    return this.price / 10;
  }//메소드 안에 this를 사용하고
}
const valueOfProduct2 = product2.getVAT();
console.log(valueOfProduct2);

//valueOfProduct2같이 객체에 넣어서 메소드를 호출하면

//this는 호출의 주체가 자기자신 (product2)가 된다

//300출력됨

 

6.

const product2 = {
  name: '가방2',
  price: 3000,
  getVAT() {
    return this.price / 10; //메소드 안에 this를 정의했지만
  }
}

const calVAT = product2.getVAT; //그 메소드를 또 변수에 저장하고
const VAT2 = calVAT();//변수를 통해 호출하면  this는 window를 가리킨다.
console.log(VAT2);

 

7.

const product2 = {
  name: '가방2',
  price: 3000,
  getVAT() {
    return this.price / 10;
  }
}

 

const newCalVAT = calVAT.bind(product2); 

//this는  bind메소드를 통해 전달한 인자값으로 변경할 수 있다.

//bind안의 인자인 product2는 리턴값으로 300을 가져서  300이 출력된다.
const VAT3 = newCalVAT();
console.log(VAT3);

 

8.

//중첩함수로 함수가 작성되었을 때의 this는 윈도우 이다.

//따라서 window.count는 undefined이므로 

//undefined+1을 1초후에 하게되면 NaN이 출력된다

const counter1 = {
  count: 0,
  addAfter1Sec() {
    setTimeout(function() {
      this.count += 1;
      console.log(this.count);
    },1000)
  }
};
counter1.addAfter1Sec();

 

9.

화살표함수의 환경에서 this는 부모환경의 this인 count:0 내의 값 0을 가리킨다.

 


const counter2= {
  count: 0,
  addAfter1Sec() {
    setTimeout(() => {
      this.count += 1;
      console.log(this.count);
    }, 1000)
  }
};
counter2.addAfter1Sec();

'javascript' 카테고리의 다른 글

157. iframe 조작하기  (0) 2022.04.25
154. 브라우저 history  (0) 2022.04.25
53. 클래스 정적 메소드와 속성  (0) 2022.04.13
49. 생성자 함수  (0) 2022.04.12
3. day7  (0) 2022.03.05