(JS) this : Dot Notation

호두파파·2021년 1월 6일
0

this

목록 보기
3/7
var age = 10;

const hodoo = {
  age: 5,
  foo: function () {
    console.log(this.age);
  }
};

const func = hodoo.foo;

// Dot Notation
hodoo.foo();

// Regular Function Call
func();

위 예제를 보면, hodoo.foo()실행문과 fuc()실행문은 결국 같은 함수를 실행한다는 것을 알 수 있다.
그러나 두가지 실행 방식의 차이에 따라 this값은 달라진다.

Dot Notation을 이용해 함수를 실행할 경우, 해당 함수 내부의 this는 Dot 앞에 있는 객체를 가리키게 된다.

즉 현재 hodoo.foo()실행문의 경우, 함수 내부의 thishodoo객체를 가리키게 된다.


예제 1

var age = 33;

function verifyAge () {
  return this.age > 21;
}

const hodoo = {
  age: 10,
  verifyAge: verifyAge
};

const beerheaven = {
  sellBeer: function (customer) {
    if (!verifyAge()) {
      return "No Beer";
    }
    
    return "Beer";
  }
};

beerheaven.sellBeer(hodoo);

함수 verifyAge는 Dot.notation으로 실행되기 때문에, beerheaven.sellBeer(hodoo)에서 arguement로 선언된 hodooagethis가 된다.

hodoo의 나이는 10이기 때문에 따라서 정답은 No Beer

예제2

function makePerson (name, age) {
  return {
    name,
    age,
    verifyAge: () => {
      return this.age > 21;
    }
  };
}

const ken = makePerson("ken", 30);

if (ken.verifyAge()) {
  alert("Yes, Beer!");
} else {
  alert("No, Beer!");
}

makePerson("ken", 30)의 실행 결과는 객체이고,
ken.verifyAge()의 결과로 실행될 함수는 다음과 같다.

verifyAge: () => {
      return this.age > 21;
    }````
// this를 찾게 되지만, 일반 함수
///makePerson("ken", 30);로 실행되고 있기 때문에 
// this는 Global Object에서 찾게된다. 결과값은 window!

따라서 결과는 No, Beer!

화살표 함수에는 this 가 존재하지 않습니다.

profile
안녕하세요 주니어 프론트엔드 개발자 양윤성입니다.

0개의 댓글