JS 기초 | 객체 (method, this)

uoah·2023년 1월 9일
0

자바스크립트

목록 보기
14/33
post-thumbnail

🚀 오늘의 학습 목표

  • method 이해
  • this 이해

14. method 와 this

14.1 method

객체 프로퍼티로 할당된 함수method 라고 한다.
아래 예제에서 fly 함수가 superman 객체의 method이다.

const superman = {
  name : 'clark',
  age : 30,
  fly : function(){
    console.log('날아갑니다');
  }
}

superman.fly();	// 날아갑니다

function 키워드를 생략하여 단축 구문으로도 사용이 가능하다.

const superman = {
  name : 'clark',
  age : 30,
  fly(){
    console.log('날아갑니다');
  }
}

superman.fly();

14-2. 객체(object) 와 메서드(method) 의 관계

const user = {
  name : 'mike',
  sayHello : function() {
    console.log(`hello, i'm ${this.name}`);
  }
}

user.sayHello();

여기에서 user 가 sayHello 함수의 this 가 된다.

14-3. this

다른 예제를 하나 보자.


let boy = {
  name : 'mike',
  sayHello : function(){
    console.log(`hello, I'm ${this.name}`);
  }
}

let girl = {
  name : 'jane',  
  sayHello : function(){
    console.log(`hello, I'm ${this.name}`);
  }
}

boy.sayHello();		// "hello, I'm mike"
girl.sayHello();	// "hello, I'm jane"

this 는 실행하는 시점 (런타임) 에 결정 된다.
sayHello 의 this. 앞에 있는 객체를 말한다.

중요한 것은 sayHello의 함수를 화살표 함수로 선언할 경우 동작이 아예 달라진다.
화살표 함수는 일반 함수와 달리 자신만의 this 를 가지지 않는다.
화살표 함수 내부에서 this 를 사용하면, this 는 외부에서 값을 가져온다.

❓ 화살표 함수를 쓰면 어떻게 될까?

let boy = {
  name : 'mike',
  sayHello : () => {
    console.log(`hello, I'm ${this.name}`); 
    // 전역 객체
  }
}
boy.sayHello();

여기에서 this != boy 이다.
여기에서 this전역객체 이다.

  • 브라우저 환경에서 전역객체 : window
  • Node js에서 전역객체 : global 을 뜻한다.

보다 자세한 this 는 다음에 따로 정리하겠다.


🧑🏻‍💻 코드로 살펴보기

여기 boy 라는 객체가 있다.
man 이라는 객체에 boy 를 할당하였다.

이는 객체를 새로 만든 것은 아니고, man 과 boy 로 접근할 수 있도록 하였다. (마치 이름은 하나인데 별명은 두 개인 것과 같은 것 🙂)

let boy = {
  name : "mike",
  showName : function (){
    console.log(boy.name);
  }
}

❓ 여기에서 man 의 name 을 Tom 으로 바꾼다면 어떻게 될까?

let man = boy;
man.showName(); // "mike"

man.name = 'Tom';
console.log(boy.name); // "Tom"

boy 의 이름도 Tom 으로 출력되는 것을 볼 수 있다.

❓ 그렇다면, boy 의 값에 null 로 만들게 되면 어떻게 될까?


let boy = {
  name : "mike",
  showName : function (){
    console.log(boy.name);
  }
}

let man = boy;
boy = null;

man.showName(); 
//Uncaught TypeError: Cannot read properties of null (reading 'name') 

name 이 없다는 에러가 난다.
boy 는 null 을 갖기 때문에 name, showName 이 모두 없는 상태이다.

이러한 문제를 해결하기 위해서는 아래와 같이 코드를 수정하면 된다.


let boy = {
  name : "mike",
  showName : function (){
    console.log(this.name);
  }
}

let man = boy;
boy = null;

man.showName(); 
//Uncaught TypeError: Cannot read properties of null (reading 'name') 

결론적으로는 메서드에서는 객체명을 직접 쓰는 것보다 this 를 써 주는 것이 좋다.

다른 예제를 보자.

let boy = {
  name : 'mike',
  sayThis: function () {
    console.log(this);
  }
};

boy.sayThis();

해당 코드를 실행해 보면 boy 객체를 반환해 준다.

❓ 만약, 화살표 함수를 쓰게 되면 어떻게 될까?

let boy = {
  name : 'mike',
  sayThis: () => {
    console.log(this);
  }
};

boy.sayThis();  // Error 

아래와 같이 이상한 오류가 나온다.

여기에서 this는 boy 를 나타내는 것이 아닌 전역 객체 를 나타낸다.

객체의 메서드를 작성할 때는 화살표 함수로 작성하지 않는 것이 좋다.

0개의 댓글

관련 채용 정보