메서드, 객체 중첩

장돌뱅이 ·2022년 1월 11일
0

JavaScript

목록 보기
20/46
  • 객체 메서드(method)
    객체에 소속된 함수를 메서드라고 부른다. 속성은 객체가 '갖는 것'이고, 메서드는 객체가 '하는 것'이다.
let retreatMessage = 'We no longer wish to conquer your planet. It is full of dogs, which we do not care for.';

// Write your code below
let alienShip = {
  retreat: function() {      // retreat이라는 메서드를 가짐. 
    console.log(retreatMessage)
  },
};
alienShip.retreat(); //We no longer wish to conquer your planet. It is full of dogs, which we do not care for. 반환

let alienShip = {         // 위와 동일한 코드 작성
  retreat () {            // function 키워드를 생략하여 작성 가능. 
    console.log(retreatMessage)
  }
};
alienShip.retreat();  //동일 값 반환 

key는 메서드 이름 역할을 하고, 값은 어떠한 함수표현을 갖는다.
메서드는 객체명.메서드명(); 으로 불러올 수 있다.

  • 객체 중첩(nested objects)
    객체는 또 다른 객체를 속성으로 가질 수 있다.
let spaceship = {
  passengers: null,
  telescope: {
    yearBuilt: 2018,
    model: "91031-XLT",
    focalLength: 2032 
  },
  crew: {
    captain: { 
      name: 'Sandra', 
      degree: 'Computer Engineering', 
      encourageTeam() { console.log('We got this!') },
     'favorite foods': ['cookies', 'cakes', 'candy', 'spinach'] }
  },
}; 

let capFave  = spaceship.crew.captain['favorite foods'][0];
console.log(capFave); // cookies 반환

spaceship.passengers = [{name: 'ememe'}];
console.log(spaceship.passengers); //[{name: 'ememe'}] 반환

0개의 댓글

관련 채용 정보