Ch.Covelope

Javascript <자바스크립트> this 본문

JavaScript

Javascript <자바스크립트> this

Chrysans 2022. 1. 27. 00:01
728x90
반응형

 

 

this 

this 는 함수가 호출되는 방식에 따라서 동적으로 결정된다.

 

 


 

 

1. 일반 함수에서 this 는 전역 객체인 window와 바인딩 된다.

console.log(this);

//window{...}

function a (){
  console.log(this)
}

a();

//window{...}

 

 


 

 

2. 메소드 안에서 this 는 메소드를 가지고 있는 오브젝트(객체)에 바인딩 된다.

let x = {
  data: "oh",
  a : function(){ console.log(this) }
}

x.a();

// { data:"oh", a: f }

 

 


 

 

 

3. 생성자 함수로 호출시 생성자 함수가 생성할 객체에 바인딩 된다.

 

function name() {
  this.first = "oh",
  this.last = "ahh"
  this.total = function(){
    console.log(this.first);
    }
}

let name1 = new name();
console.log(name1)
//{first: 'oh', last: 'ahh', total: ƒ}

 

 


 

 

 

this값은 함수를 만날 때마다 바뀔 수 있기 때문에 본인이 원하는 this를 쓰기 힘든 경우가 발생할 수 있는데 그럴 때 화살표 함수를 로 사용하면 내부의 this를 새로 바꾸지 않기 때문에 의도에 맞게 사용할 수 있을 거 같다.

var obj = {
  name : ['kim', 'lee', 'jay'],
  func : function(){
      obj.name.forEach(() => {
        console.log(this)
      });
  }
}

obj.func()

//{name: Array(3), func: ƒ} * 3

 

 

 


 

 

 

 

https://github.com/chry8822

 

chry8822 - Overview

‘Keep true to the dreams of thy youth’ . chry8822 has 22 repositories available. Follow their code on GitHub.

github.com

 

 

 

 

728x90
반응형
Comments