JS Object 메소드와 중첩된 객체

Joah·2022년 5월 29일
0

Javascript

목록 보기
5/16
post-thumbnail

Method (메서드)

객체에 저장된 값이 함수일 때, 메서드라고 부른다.

메서드 작성해보기

const mike = {
	name: "Mike",
 	position: ["chief", "line-cook manager"],
  	age: 25,
  	fulltime: true,
  	secondRole: function(){
    	console.log(mike.position[1])
    }
};

mike.secondRole();
//"line-cook manager"
  • 메서드를 사용할 때는 함수를 호출하 듯 key에 대괄호를 붙인다.
  • 객체의 value를 얻어올 때 점 표기법 또는 대괄호를 사용해서 key를 불러오는 것과 같은 방법
    즉, mike.name로 "Mike" 불러오는 것처럼 메소드 또한 mike.secondRole()로 접근한다.


중첩된 객체 (Nested Object)

실무에서 사용되는 객체는 거의 중첩되어 있다. 프로퍼티 값이 객체일 수도 있고, 프로퍼티 값인 배열의 요소가 객체일 수도 있다.

const mike = {
	name: "Mike",
 	position: ["chief", "line-cook manager"],
  	age: 25,
  	fulltime: true,
  	experiences: {
    	asia : {
        	korea : "2years",
          	china : "1year",
          	thailand : "3years"
        },
      	america : {
        	mexico : "6months",
          	canada : "2years"
        },
      	certificates : {
        	food: [{
            	name: "Fried Chicken",
              	licenseNumber: 25 
            }, {
            	name: "Rice noodle",
              	licenseNumber: 423
            }, {
            	name: "Fries with Gravy",
              	licenseNumber: 574
            }]
        }
    },
  	secondRole: function(){
    	console.log(mike.position[1])
    }
};

위에서 423 을 출력하려면 어떻게 해야할까?

  • mike.experience에는 asia, america, certificates가 있다.
  • 423을 출력하기 위해서는 certificates에 접근해야 한다.
//certificates의 value까지 접근하기
mike.experiences.certificates

  • certificates객체 안에 food라는 하나의 객체가 더 있다.
mike.experiences.certificates.food

  • food는 배열 데이터를 값으로 가지고 있다. 423은 food 배열에서 index number 1번 째에 있으며 배열 안의 객체에서 key 이름licenseNumber의 value이다.
mike.experiences.certificates.food[1].licenseNumber

//너무 기니깐 변수에 담아보자
const result = mike.experiences.certificates.food[1].licenseNumber

console.log(result);
// 423



지난 포스트에서...

const는 상수인데 점 표기법, 대괄호 표기법으로 const에 할당된 값을 수정, 삭제, 추가할 수 있는 이유

객체를 변수에 저장하면 객체 자체가 저장되는 것이 아니라 reference가 저장된다.
Object, array, function 등 원시형이 아닌 모든 데이터 타입을 참조형 reference이다.

반대로, 텍스트는 변수에 저장하면 텍스트 자체가 저장된다. 그래서 서로 같은 텍스트를 비교연산 하면 서로 값이 같으므로 true 이다.
String, Number, Boolean, Null,undefined의 데이터 타입은 모두 원시형 primitive이다.

원시형 데이터 String비교

const a = '안녕';
const b = '안녕';
console.log(a === b);
//true

BUT!! 아래의 객체는 생긴 모양이 아예 똑같은데 false 라고 출력된다.

const hiObj = { 
  name: '안녕' 
};
const helloObj = {
  name: '안녕'
};
console.log(hiObj === helloObj);
//false

그 이유는 객체는 변수에 저장할 때, 객체 자체를 그대로 저장하는 것이 아니라 객체가 담긴 어느 메모리의 reference 를 저장하기 때문이다.

자세한 내용은 [데이터의 불변성] 포스트를 추후 작성한다면 그때 다시 다룰 것이다.

profile
Front-end Developer

0개의 댓글