This 키워드는 문맥에 따라 가르키는 객체가 다르며 대개 아래의 5가지 방식이 있다.

 

1) 전역객체 (Global Object)

console.log(this)  // Window { ... }
결과값은 Window{ ... } 즉 this는 글로벌 객체를 가리킨다.

2) 객체선언 (Declared Object) // 자신이 속한 함수를 포함한 가장 가까운 객체의 프로퍼티를 가리킨다

var person = {
  firstName: "Dale",
  lastName: "John",
  fullName: function() { this.firstName + ' ' + this.lastName}
 }
 person.fullName();   // Dale John

3) 객체생성(new keyword)  // constructor를 만들어서 객체생성하면 클래스처럼 재활용 가능

function Person(firstName, lastName) {
  this.firstName = firstName;  // var firstName = firstName
  this.lastName = lastName;
};
var myName = new Person('Dale', 'John');
console.log(myName);   // firstName: Dale, lastName: John

4) call, apply and bind

function add(c, d) {
  this.a = 1;
  this.b = 2;
  console.log(this.a + this.b + c + d);
}
add(3,4);  // 10
 
// What if
function add(c, d) {
  console.log(this.a + this.b + c + d);
}
add(3,4);  
// NaN 
// this.a 와 this.b 가 무엇을 가리키는지 알수 없음. 미리 만들어진 객체를 가져다 
쓸 수 있으며 아래와 같이 사용
// 만들어진 메소드 사용할때 내부에 this로 연산시
var plus = {a:1, b:2};
add.call(plus, 3, 4);     add.apply(plus, [3,4]);

// 객체내 함수 사용의 경우
var family = {
  son: 1,
  total: function(dad, mom, daughter) {
    console.log(this.son + dad + mom + daughter);
  }
}
family.total(30,26,5);  // 62  normal case

var large = { son: 2; }   // 알고보니 아들이 2살
family.total.call(large, 30, 26, 5);  // 62  call 적용

// bind - this를 가지고 있으나 실행하지 않고 있음, 파라미터의 값을 모를때 사용
// 가리키는 객체를 우선 바인드 해주는 것
var bindTest = family.total.bind(large, 40);  // large와 Dad값만 넣어둠
bindTest(36,5);  // 나머지 값도 넣어줌

5) 화살표 함수 (Arrow Function)

   - 간결한 함수를 만들어줌

   - binding 되지 않은 this

     : this값의 정의는 생성자를 통한 새로운 객체, 엄격모드에서의 undefined, 객체 메서드로서의 호출되는 경우는

      문맥의 객체로 결정됨

function Counter() {
  this.num = 0;
  this.timer = setInterval(function() {
    this.num++;  // 함수내에서의 this는 바깥에 있는 전역 객체를 가리키나 num이 존재하지 않음
    console.log(this.num);
  }, 1000);
}

// 따라서 다음과 같이 할당하여 사용
function Counter() {
  var that = this;
  that.num = 0;
  that.timer = setInterval(function() {
    that.num++;
    console.log(that.num);
  }, 1000);
}

// ECMA6 에서의 화살표 함수는 자신의 this가 없고, 바인딩한 함수를 둘러싸는 렉시컬 범위(scope)의
// this 가 사용됨. 화살표 함수의 this는 본인의 함수가 포함된 function의 this값과 동일함
function Counter() {
  this.num = 0;
  this.timer = setInterval(() => [
    this.num++;
    console.log(this.num);
  }, 1000);
}
var c = new Counter();

'JavaScript' 카테고리의 다른 글

정규식  (0) 2020.12.03
Prototype  (0) 2020.12.03
즉시 실행 함수(IIFE: Immediately Invoked Function Expression)  (0) 2020.12.02
Callback, Promise, Observable and Async/await  (0) 2020.12.02
JavaScript Object  (0) 2020.11.28

+ Recent posts