Javascript/객체

Javascript 객체 안에 함수 넣는방법 feat.화살표함수

appmaster 2021. 1. 31. 16:22

총 3가지 방법이 있습니다.

 

 

1. say: function say()

const dog = {
  name: "멍멍이",
  sound: "멍멍!",
  say: function say() {
    console.log(this.sound);
  }
};

dog.say();

 

 

 

2. say: function ()

const dog = {
  name: "멍멍이",
  sound: "멍멍!",
  say: function() {
    console.log(this.sound);
  }
};

dog.say();

 

 

 

3. say()

const dog = {
  name: "멍멍이",
  sound: "멍멍!",
  say() {
    console.log(this.sound);
  }
};

dog.say();

 

 

 

**주의점!** 화살표함수를 사용하면 작동이 되지 않습니다.

const dog = {
  name: "멍멍이",
  sound: "멍멍!",
  say: ()=> {
    console.log(this.sound);
  }
};

dog.say();
//출력값
TypeError: Cannot read property 'sound' of undefined

function 키워드들은 자신이 속해있는곳을 가리키게 되는데, 화살표함수는 this를 자신이 속해있는곳으로 연결하지 않습니다.

 

'Javascript > 객체' 카테고리의 다른 글

Javascript --> getter와 setter 함수  (0) 2021.01.31
class, constructor  (0) 2021.01.26
Object  (0) 2021.01.26
객체 지향 프로그램으로 하기  (0) 2020.08.02