[Study/JavaScript] 객체 / method

SoShy·2023년 11월 28일

JavaScript_Study

목록 보기
9/36
post-thumbnail

🥕 객체 (Object)

  • 기본 구조: {key: value}
  • keyvalue는 쉼표(,)를 통해 구분

  • keyvalue 한 쌍을 개체의 속성(Property) 이라고 함.
  • 그래서 keyProperty Name이라고도 하며, valueProperty Value라고도 함.

  • Property Name은 문자열 타입을 가지고 있음.
    - 따옴표로 감싸주지 않아도 암시적 형변환이 일어남.
{
  brandName: '소샤이',
  bornYear: 2017,
  isVeryNice: true,
  worstCourse: null
}

  • Property Value는 모든 자료형 사용 가능
  • 아래와 같이 객체 안에 객체를 집어넣는 것도 가능
{
  bestCourse: {
    title: '소샤이에 대하여',
    language: 'JavaScript'
  }
}

  • typeof 연산자를 통해 자료형 확인 가능
console.log(typeof {
  bestCourse: {
    title: '소샤이에 대하여',
    language: 'JavaScript'
  }
}) 
.
.
.
>>> object

1. Property Name 작성 시 주의 사항

  • 첫 번째 글자는 반드시 문자(''), 밑줄(_), 달러 기호($) 중 하나로 시작
    (사실 숫자도 되지만... 그건 나중에...)
  • 띄어쓰기 금지
  • 하이픈(-) 금지

  • 규칙을 벗어나서 작성하고 싶을 때는, 따옴표('')로 감싸주면 가능

2. 객체에서 데이터 접근하기

1) 점 표기법

  • 객체의 property에 접근하는 가장 간단하고 많이 사용되는 방식
  • 따옴표를 생략할 수 없는 property name으로는 접근 불가능
let rabbit = {
  name: '소샤이',
  bornYear: 2017,
  isVeryNice: true,
  worstCourse: null,
  bestCourse: {
    title: '소샤이에 대하여',
    languege: 'JavaScript'
  }
}

console.log(rabbit.bornYear);
.
.
.
>>> 2017

2) 대괄호 표기법

  • 점 표기법에 비해 property name을 더 유연하게 구성할 수 있음.
  • method에서 parameter로 다른 변수에 담긴 값을 가져올 때는 반드시 대괄호 표기법 사용
let rabbit = {
  name: '소샤이',
  bornYear: 2017,
  isVeryNice: true,
  worstCourse: null,
  bestCourse: {
    title: '소샤이에 대하여',
    languege: 'JavaScript'
  }
}

console.log(rabbit['born Year']);
console.log(rabbit['born ' + 'Year']);
.
.
.
>>> 2017
	2017
let rabbit = {
  name: '소샤이',
  bornYear: 2017,
  isVeryNice: true,
  worstCourse: null,
  bestCourse: {
    title: '소샤이에 대하여',
    languege: 'JavaScript'
  }
}

let propertyName = 'name';
console.log(rabbit[propertyName]);
.
.
.
>>> 소샤이

3) 객체 안의 객체에 접근하는 방법

let rabbit = {
  name: '소샤이',
  bornYear: 2017,
  isVeryNice: true,
  worstCourse: null,
  bestCourse: {
    title: '소샤이에 대하여',
    languege: 'JavaScript'
  }
}

console.log(rabbit.bestCourse.title);
.
.
.
>>> 소샤이에 대하여

아래와 같이, 존재하지 않는 property에 접근하고자 하면, undefined 값 출력됨.

let rabbit = {
  name: '소샤이',
  bornYear: 2017,
  isVeryNice: true,
  worstCourse: null,
  bestCourse: {
    title: '소샤이에 대하여',
    languege: 'JavaScript'
  }
}

console.log(rabbit.bestCourse['teacher']);
.
.
.
>>> undefined

3. 객체 다루기

1) 객체의 property 수정하기

let rabbit = {
  name: '소샤이',
  bornYear: 2017,
  isVeryNice: true,
  worstCourse: null,
  bestCourse: {
    title: '소샤이에 대하여',
    languege: 'JavaScript'
  }
}

console.log(rabbit.name);

codeit.name = 'SoShy';
console.log(rabbit.name);
.
.
.
>>> 소샤이
	SoShy

2) 객체에 property 추가하기

let rabbit = {
  name: '소샤이',
  bornYear: 2017,
  isVeryNice: true,
  worstCourse: null,
  bestCourse: {
    title: '소샤이에 대하여',
    languege: 'JavaScript'
  }
}

console.log(rabbit.friend);

codeit.friend = '망토';
console.log(rabbit.friend);
.
.
.
>>> undefined
	망토

3) 객체의 property 삭제하기

let rabbit = {
  name: '소샤이',
  bornYear: 2017,
  isVeryNice: true,
  worstCourse: null,
  bestCourse: {
    title: '소샤이에 대하여',
    languege: 'JavaScript'
  }
}

console.log(rabbit.worstCourse);

delete rabbit.worstCourse;
console.log(rabbit.worstCourse);
.
.
.
>>> null
	undefined

4) 객체의 property 존재 여부 확인

  • 아래와 같은 방법으로 property 존재 여부 확인은 가능하지만, in 연산자를 통해 확인하는 것을 권장함.
    - 실수로 property valueundefined를 할당한다거나, 다른 함수나 변수에 의해 의도치 않게 undefined 값이 할당될 수도 있기 때문
let rabbit = {
  name: '소샤이',
  bornYear: 2017,
  isVeryNice: true,
  worstCourse: null,
  bestCourse: {
    title: '소샤이에 대하여',
    languege: 'JavaScript'
  }
}

console.log(rabbit.name !== undefined);
.
.
.
>>> true

4. in 연산자

  • property의 존재 여부 확인

  • boolean 형태로 값 return
    (if문에서 조건 부분에 활용하기 좋음)

let rabbit = {
  name: '소샤이',
  bornYear: 2017,
  isVeryNice: true,
  worstCourse: null,
  bestCourse: {
    title: '소샤이에 대하여',
    languege: 'JavaScript'
  }
}

console.log('name' in rabbit);
.
.
.
>>> true
let rabbit = {
  name: '소샤이',
  bornYear: 2017,
  isVeryNice: true,
  worstCourse: null,
  bestCourse: {
    title: '소샤이에 대하여',
    languege: 'JavaScript'
  }
}

if ('name' in rabbit) {
  console.log(`name 값은 ${rabbit.name}입니다.`);
} else {
  console.log(`name property는 존재하지 않습니다.`);
}
.
.
.
>>> name 값은 소샤이입니다.


🥕 method

  • 객체의 property 값에 할당된 함수
  • 함수 이름은 property name이 대신 해주기 때문에 따로 지정할 필요 없음.
let greetings = {
  sayHello: function () {
    console.log('Hello!');
  },
  sayHi: function () {
    console.log('Hi!');
  },
  sayBye: function () {
    console.log('Bye!');
  }
}

greetings.sayHello();
.
.
.
>>> Hello!
let greetings = {
  sayHello: function (name) {
    console.log(`Hello ${name}!`);
  },
  sayHi: function () {
    console.log('Hi!');
  },
  sayBye: function () {
    console.log('Bye!');
  }
}

greetings.sayHello('Shy');
.
.
.
>>> Hello Shy!

  • 대괄호 표기법 사용 가능
let greetings = {
  sayHello: function (name) {
    console.log(`Hello ${name}!`);
  },
  sayHi: function () {
    console.log('Hi!');
  },
  sayBye: function () {
    console.log('Bye!');
  }
}

greetings['sayHello']('shy');
.
.
.
>>> Hello shy!
profile
프론트엔드 개발자가 되기 위해 노력 중인 새싹🌱 입니다.

0개의 댓글