TIL 004 | 객체(Object)와 메서드(Method)

김태규·2021년 7월 26일
0
post-thumbnail

객체(Object)와 메서드(Method)란

자바스크립트는 객체(object) 기반의 스크립트 언어이며 자바스크립트를 이루고 있는 거의 “모든 것”이 객체이다. 원시 타입(Primitives)을 제외한 나머지 값들(함수, 배열 등)은 모두 객체이다.

자바스크립트의 객체는 키(key)과 값(value)으로 구성된 프로퍼티(property)들의 집합이다. 프로퍼티의 값으로 자바스크립트에서 사용할 수 있는 모든 값을 사용할 수 있다. 이 때 프로퍼티 값으로 함수를 사용할 수도 있으며 프로퍼티 값이 함수일 경우, 일반 함수와 구분하기 위해 메서드(method)라 부른다.


객체(object)는 프로퍼티(property)를 가진 데이터를 저장해주며, 괄호{ }를 사용한다.

const something = {
	name: 'apple',
  	color: 'red',
  	fruit: true
};

프로퍼티를 불러오는 방법은 2가지가 있다.

something.name  //  apple
something["name"]  //  apple

또한 프로퍼티를 바꾸는 것이 가능하다.

console.log(something.color);   // red
something.color = "blue";
console.log(something.color);   // blue

그리고 프로퍼티를 추가할 수도 있다.

something.koreanName = '사과';
console.log(something); // {name: 'apple', color: 'red', fruit: true, koreanName: '사과'}

마지막으로 프로퍼티를 삭제할 수도 있다.

delete something.fruit
console.log(something)  // {name: 'apple', color: 'red'}

프로퍼티의 값으로 함수가 올 수도 있는데, 이러한 프로퍼티를 메서드(method)라고 한다.

const something = {
	name: 'apple',
  	color: 'red',
  	fruit: true,
  	colorAndName: function() {
    		return this.color + ' ' + this.name;
    	}
};

메서드를 불러오는 방법은 다음과 같다.

something.colorAndName();  // red apple

references

https://poiemaweb.com/js-object

0개의 댓글

관련 채용 정보