Notice
Recent Posts
Recent Comments
Link
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Archives
Today
Total
관리 메뉴

Far from it.

객체 리터럴에서 'this' 사용하기 본문

JS

객체 리터럴에서 'this' 사용하기

두유콩 2020. 4. 22. 13:58

https://ko.javascript.info/task/object-property-this

 

객체 리터럴에서 'this' 사용하기

함수 makeUser는 객체를 반환합니다. 이 객체의 ref에 접근하면 어떤 결과가 발생하고, 그 이유는 뭘까요? function makeUser() { return { name: "John", ref: this }; }; let user = makeUser(); alert( user.ref.name ); // 결과가 어떻게 될까요? 해답 에러가 발생합니다. 직접 실행해 봅시다. function makeUser() { return { name: "John

ko.javascript.info

this의 값은 호출 시점에서 결정되고, makeUser는 메서드로써 호출된게 아닌 함수로써 호출되었기 때문에 undefined가 나온다.

 

에러가 발생하지 않게 하기 위해서는 ref 프로퍼티를 메서드로 만들어주면 된다

function makeUser() {
  return {
    name: "John",
    ref() {
      return this;
    }
  };
};

let user = makeUser();

alert( user.ref().name ); // John

 

'JS' 카테고리의 다른 글

Animate.css  (0) 2020.04.22
계산기 만들기  (0) 2020.04.22