this

javascript의 this 키워드는 다른 언어와는 조금 다르게 동작한다.

실행컨텍스트(EC, Execution Context)가 생성될때마다 this의 바인딩이 일어나며 우선순위가 있다.

대부분은 함수를 호출한 방법에 의해 this가 결정된다. 따라서 함수의 호출때마다 다를수도 있다.

 

1. new 는 해당객체

2. call, apply, bind 같은 명시적 바인딩일 경우 인자로 전달된 객체

3. 객체의 메소드로 호출한 경우 해당 객체

4. 그외 엄격모드는 undefined로 초기화 됨 (엄격, 비엄격에 차이가 있다)

5. 글로벌에서 일반 브라우저는 window, 노드는 global

 


전역 문맥

전역 실행 문맥에서의 this는 엄격모드 여부에 관계없이 전역 객체를 참조합니다.

// 브라우저 전역 객체는 window
console.log(this === window); // true

 

함수 문맥 

호출한 방법에 의해 this가 결정된다.

같은 코드라도 엄격모드 비엄격모드에서 달라질 수 있다.

// 비엄격모드
function test() {
  return this;
}

test() === window; // true

// 엄격모드
functiontest(){
  "use strict"; 
  return this;
}

test() === undefined; // true

this의 값을 한 문맥에서 다른 문맥으로 넘기려면 call, apply 메서드를 사용할 수 있습니다.

 

 

bind

ECMAScript 5에서는 Function.prototype.bind를 도입

bind는 함수를 어떻게 호출했는지 상관하지 않고 this를 설정할 수 있다.

this는 bind()의 첫 번째 매개변수로 고정.

function test() {
  return this.a;
}

var test1 = f.bind({a: 'azerty'});
console.log(g()); // azerty

var h = g.bind({a: 'yoo'}); // bind는 한 번만 동작함!
console.log(h()); // azerty

var o = {a: 37, f: f, g: g, h: h};
console.log(o.a, o.f(), o.g(), o.h()); // 37, 37, azerty, azerty

 

arrow function

ES6에서는 스스로 this 바인딩을 제공하지 않는 화살표 함수를 추가.

이때는 실행컨텍스트안의 this값을 유지.

const car = {
	name : avante,
	getPrice: function() {
	return this.name;
  },
};

console.log(car.name()); // avante

 

 


 

this의 바인딩

https://github.com/baeharam/Must-Know-About-Frontend/blob/master/Notes/javascript/this.md

 

mdn 

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Operators/this

 

+ Recent posts