자바스크립트 입문

LeeKyoungChang·2022년 10월 14일
0
post-thumbnail

벨로퍼트와 함께하는 모던 자바스크립트 문서를 참고한 후 정리한 내용입니다.

 

📚 1. JavaSciprt 출력

JavScript는 웹 브라우저에서 사용하기 위하여 만들어진 프로그래밍 언어

 

💡 참고
실행 : cmd + ctrl + n

 

console.log('Hello JavaScript');

 

 

📚 2. 변수와 상수

let : 변수
console : 상수

선언 : 특정 이름에 특정 값을 설정하는 것

 

📖 A. 변수

let은 변수

변수는 바뀔 수 있는 값을 말한다.
한번 값을 선언하고 나서 바꿀 수 있다.

let value = 1;
console.log(value); // 결과 : 1

변수를 선언 할 때는 let 이라는 키워드를 사용한다.

 

📖 B. 상수

const 은 상수

상수 : 한번 선언하고 값이 바뀌지 않는 값을 의미한다. 값이 고정적이다.

const a = 1;

상수를 선언하고 나면, 값을 바꿀 수 없다.

const a = 1;
a = 2; // a is read-only

 

💡 참고
더이상 var는 사용하지 말자! (이전 버전에서 사용되던 변수이다. 현재는 사용되고 있지 않다.)

 

📖 C. 데이터타입

✔️ 숫자(Number)

let value = 1;

 

✔️ 문자열(String)

let text = 'hello';
let name = '자바스크립트';
  • 작은 따옴표와 큰 따옴표 사용에 있어서 큰 차이가 없다.

 

✔️ 참/거짓(Boolean)

let good = true;
let loading = false;

 

✔️ null과 undefined

const friend = null; // null
let criminal;
console.log(criminal); // undefined
  • null : 값이 없다. (우리가 없다.)
  • undefined : 우리가 설정을 하지 않았기 때문에 없는 값이다.

 

 

📚 3. 연산자

✔️ 논리 연산자

! : NOT
&& : AND
|| : OR

연산자 순서 : NOT -> AND -> OR

 

✔️ 비교 연산자

== : 자료형을 보지 않고 두 값이 일치하는지 비교하는 연산자
=== : 자료형을 보고 두 값이 일치하는지 비교하는 연산자

const a = 1;
const b = `1`;
console.log(a == b); // true


console.log(a === b); // false

 

!== : 두 값이 일치하지 않는지 확인할 때 사용
!= : 타입 검사를 하지 않고 두 값이 일치하지 않는지 확인할 때 사용

 

 

📚 4. 함수

funciton add(a, b){
	return a + b;
}

const sum = add(1, 2);
console.log(sum); // 3

 

✔️ 문자열 함수로 합치기

function hello(name){
	console.log('Hello, ' + name + '!');
}
hello('velopert'); // 결과 : Hello, velopert

 

✔️ ES6란 무엇인가?

ES6 : ECMAScript6, 자바스크립트의 버전을 가리킨다.

 

function hello(name){
	console.log(`Hello, ${name}!`);
}
hello('velopert');

 

✔️ 화살표 함수

const add = (a, b) => {
	return a + b;
};

console.log(add(1, 2));
  • 화살표의 좌측 : 함수의 파라미터
  • 화살표의 우측 : 코드 블록
const add = (a, b) => a + b;
console.log(add(1, 2));

 

💡 참고
함수가 내부적으로 여러 줄로 구성되어 있는 경우에는 코드 블록으로 만들어야 한다.
function fun(){}

 

 

📚 5. 객체

✔️ 객체란?
변수 혹은 상수를 사용하게 될 때 하나의 이름에 여러 종류의 값을 넣을 수 있게 해준다.

ex)

const dog = {
	name : '멍멍이',
	age : 2
};

console.log(dog.name);
console.log(dog.age);

결과

멍멍이
2

 

객체를 선언할 때는 {} 문자 안에 원하는 값들을 넣어주면 된다.

키 : 원하는 값

키에 해당하는 부분은 공백이 없어야 한다.

만약 공백이 있을 경우 따옴표로(') 로 감싸서 문자열로 넣어주면 된다.

const sample = {
	'key with space' : true
}

 

ex) 두 가지의 객체를 생성하여 출력하기

const ironMan = {
	name : '토니 스타크',
	actor : '로버트 다우니 주니어',
	alias : '아이언맨'
};

const captainAmerica = {
	name : '스티븐 로저스',
	actor : '크리스 에반스',
	alias : '캡틴 아메리카'
};

console.log(ironMan);
console.log(captainAmerica);

 

✔️ 함수에서 객체를 파라미터로 받기

const ironMan = {
	name : '토니 스타크',
	actor : '로버트 다우니 주니어',
	alias : '아이언맨'
};

const captainAmerica = {
	name : '스티븐 로저스',
	actor : '크리스 에반스',
	alias : '캡틴 아메리카'
};

function print(hero){
	const text = `${hero.alias}(${hero.name}) 역할을 맡은 배우는 ${hero.actor} 입니다.`;
	console.log(text);
}

print(ironMan);
print(captainAmerica);
아이언맨(토니 스타크) 역할을 맡은 배우는 로버트 다우니 주니어 입니다.
캡틴 아메리카(스티븐 로저스) 역할을 맡은 배우는 크리스 에반스 입니다.

 

✔️ 객체 비구조화 할당

객체 구조 분해

const ironMan = {
	name : '토니 스타크',
	actor : '로버트 다우니 주니어',
	alias : '아이언맨'
};

const captainAmerica = {
	name : '스티븐 로저스',
	actor : '크리스 에반스',
	alias : '캡틴 아메리카'
};

function print(hero){
	const { alias, name, actor} = hero;
	const text = `${alias}(${name}) 역할을 맡은 배우는 ${actor} 입니다.`;
	console.log(text);
}

print(ironMan);
print(captainAmerica);
const { alias, name, actor} = hero;
  • 객체에서 값들을 추출해서 새로운 상수로 선언

파라미터 단계에서 객체 비구조화 할당

const ironMan = {
	name : '토니 스타크',
	actor : '로버트 다우니 주니어',
	alias : '아이언맨'
};

const captainAmerica = {
	name : '스티븐 로저스',
	actor : '크리스 에반스',
	alias : '캡틴 아메리카'
};

function print({ alias, name, actor}){	
	const text = `${alias}(${name}) 역할을 맡은 배우는 ${actor} 입니다.`;
	console.log(text);
}

print(ironMan);
print(captainAmerica);

 

✔️ 객체 안에 함수 넣기

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

dog.say();
멍멍!

 

  • this : 자신이 속해있는 객체를 가리킨다.
  • 함수를 선언할 때 이름이 없어도 된다.
  • this는 자신이 속한 객체를 가르킨다. 화살표 함수는 그렇지 않다.

 

📖 A. Getter 함수와 Setter 함수

Getter 함수 : 특정 값을 바꿀 때
Setter 함수 : 특정 값을 조회할 때

 

✔️ Getter

const numbers = {
	a : 1,
	b : 2,
	get sum() {
		console.log('sum 함수가 실행된다.');
		return this.a + this.b;
	}
};

console.log(numbers.sum);
numbers.b = 5;
console.log(numbers.sum);
  • number.sum을 조회했을 뿐이지만 함수가 실행되고 그 결과값이 출력되었다.
  • Getter 함수는 특정 값을 조회할 때 설정한 함수로 연산된 값을 반환한다.
  • get을 함수앞에 붙여준다.

 

✔️ Setter

const numbers = {
	_a : 1,
	_b : 2,
	sum : 3,
	calculate(){
		console.log('calculate');
		this.sum = this._a + this._b;
	},
	get a(){
		return this._a;
	},
	get b(){
		return this._b;
	},
	set a(value){
		console.log('a가 바뀝니다.');
		this._a = value;
		this.calculate();
	},
	set b(value){
		console.log('b가 바뀝니다.');
		this._b = value;
		this.calculate();
	}
};

console.log(numbers.sum);
numbers.a = 5;
numbers.b = 7;
numbers.a = 9;
console.log(numbers.sum);
console.log(numbers.sum);
console.log(numbers.sum);
  • Setter 함수를 설정할 때에는 함수의 앞부분에 set 키워드를 붙인다.
  • 이전에는 만든 객체에서 numbers.sum 이 조회 될 때마다 덧셈이 이루어졌지만, 이제는 a 혹은 b 값이 바뀔 때마다 sum 값을 연산한다.

 

 

📚 6. 배열

배열 : 여러 개의 항목들이 들어있는 리스트와 같다.

const array = [1,2,3,4,5];

배열을 선언할 때에는 [] 안에 감싸주면 된다.

 

✔️ 객체 배열이란?

const object = [{ name : '멍멍이'}, {name : '야옹이'}];

배열을 선언하고 나서, n번째 항목을 조회하고 싶을 때

objects[n];

ex) 객체 배열 입출력 예시

const objects = [{name : '멍멍이'}, {name : '야옹이'}];

console.log(objects);
// [Object, Object]
// 0 : Object
// - name : "멍멍이"
// 1 : Object
// - name : "야옹이"

console.log(objects[0]);
// Object {name : "멍멍이"}

console.log(objects[1]);
// Object {name : "야옹이"}

 

✔️ 배열에 새 항목 추가하기

배열에 새로운 항목을 추가할 때는 배열이 지니고 있는 내장 함수인 push 함수를 사용한다.

const objects = [{name : '멍멍이'}, {name : '야옹이'}];

objects.push({
	name : '멍뭉이'
});

console.log(objects);
[Object, Object, Object]
0 : Object
	name : "멍멍이"
1 : Object
	name : "야옹이"
2 : Object
	name : "멍뭉이"

 

✔️ 배열의 크기 알아내기

length : 배열의 크기를 알아낼 때 사용한다.

const objects = [{name : '멍멍이'}, {name : '야옹이' }];

console.log(objects.length); // 2

objects.push({
	name : '멍뭉이'
});


console.log(objects.length); // 3

 

 

📚 7. 반복문

📖 A. for문

for(let i = 0; i < 10; i++){
	console.log(i);
}

 

✔️ for...of

let numbers = [10, 20, 30, 40, 50];

for(let number of numbers){
	console.log(number);
}

// 10
// 20
// 30
// 40
// 50

 

✔️ 객체를 위한 반복문 for...in

const doggy = {
	name : '멍멍이',
	sound : '멍멍',
	age : 2
};

console.log(Object.entires(doggy));
// [Array[2], Array[2], Array[2]]
// 0 : Array[2]
//  0 : "name"
//  1 : "멍멍이"
// 1 : Array[2]
//  0 : "sound"
//  1 : "멍멍"
// 2 : Array[2]
//  0 : "age"
//  1 : 2

console.log(Object.keys(doggy));
// ["name", "sound", "age"]

console.log(Object.values(doggy));
// ["멍멍이", "멍멍", 2]
  • Object.entires : [[키, 값], [키, 값]] 형태의 배열로 변환
  • Object.keys. : [키, 키, 키] 형태의 배열로 변환
  • Object.values : [값, 값, 값] 형태의 배열로 변환

객체가 지니고 있는 값에 대하여 반복을 하고 싶다면 위와 같은 함수를 사용한다.
또는 for...in 구문을 사용해도 된다.

const doggy = {
	name : '멍멍이',
	sound : '멍멍',
	age : 2
};


for(let key in doggy){
	console.log(`${key}: ${doggy[key]}`);
}

 

 

📚 8. 배열 내장함수

📖 A. forEach

가장 쉬운 배열 내장함수

 

✔️ for문과 foreach문

for문

const superheroes = ['아이언맨', '캡틴 아메리카', '토르', '닥터 스트레인지'];

for(let i = 0; i< superheroes.length; i++){
	console.log(superheroes[i]);
}

 

const superheroes = ['아이언맨', '캡틴 아메리카', '토르', '닥터 스트레인지'];

superheros.forEach(hero => {
	console.log(hero);
});
  • forEach 함수의 파라미터로 각 원소에 대하여 처리하고 싶은 코드를 함수로 넣어준다.
  • 함수의 파라미터 hero는 각 원소를 가르키게 된다.

 

💡 참고
콜백함수 : 함수형태의 파라미터를 전달하는 것 (함수를 등록해주면, forEach가 실행을 해준다.)

 

 

📖 B. map

map : 배열 안의 각 원소를 변환할 때 사용되며, 이 과정에서 새로운 배열이 만들어진다.

const array = [1, 2, 3, 4, 5, 6, 7, 8];

 

배열 안의 모든 숫자를 제곱해서 새로운 배열을 만들고 싶다면?
=> map 함수를 사용하지 않고 이전까지 배운 지식을 활용하면 된다.

const array = [1,2,3,4,5,6,7,8];

const squared = [];
for (let i = 0; i < array.length; i++){
	squared.push(array[i] * array[i]);
}

console.log(squared);

 

forEach를 쓰면 이와같이 구현할 수도 있다.

const array = [1,2,3,5,6,7,8];

const squared = [];

array.forEach(n => {
	squared.push(n * n);
});

console.log(squared);

결과

[1, 4, 9, 16, 25, 36, 49, 64];

위 내용을 map을 사용할 시 더 짧은 코드를 사용하여 구현할 수 있다.

const array = [1, 2, 3, 4, 5, 6, 7, 8];

const square = n => n * n;
const squared = array.map(square);
console.log(squared);
  • square 함수는 n을 받아와서 이를 제곱해준다.
  • array.map 함수를 사용할 때 square를 변화함수로 사용함으로써, 내부의 모든 값에 대하여 제곱을 해서 새로운 배열을 생성했다.

 

✔️ map 함수는?

변화 함수 : map 함수의 파라미터, 변화를 주는 함수를 전달해준다.

const squared = array.map(n => n * n);
console.log(squared);

 

 

✔️ indexOf

indexOf : 원하는 항목이 몇번째 원소인지 찾아주는 함수

ex)

const superheroes = ['아이언맨', '캡틴 아메리카', '토르', '닥터 스트레인지'];
const index = superheroes.indexOf('토르');
console.log(index); // 2
  • 0 : 아이언맨, 1 : 캡틴 아메리카, 2 : 토르

 

✔️ findIndex

배열 안에 있는 값이 숫자, 문자열, 불리언이라면 찾고자하는 항목이 몇번째 원소인지 알아내기 위해 indexOf를 사용하면 된다.

 

배열 안에 있는 값이 객체 or 배열이라면 indexOf로 찾을 수 없다.

const todos = [
	{
		id : 1,
		text : '자바스크립트 입문',
		done : true
	},
	{
		id : 2,
		text : '함수 배우기',
		done : true
	},
	{
		id : 3,
		text : '객체와 배열 배우기',
		done : true
	},
	{
		id : 4,
		text : '배열 내장함수 배우기',
		done : false
	}
];
  • 만약 id가 3인 객체가 몇번째인지 찾으려면, findIndex 함수에 검사하고자 하는 조건을 반환하는 함수를 넣어서 찾을 수 있다.

 

const todos = [
	{
		id : 1,
		text : '자바스크립트 입문',
		done : true
	},
	{
		id : 2,
		text : '함수 배우기',
		done : true
	},
	{
		id : 3,
		text : '객체와 배열 배우기',
		done : true
	},
	{
		id : 4,
		text : '배열 내장함수 배우기',
		done : false
	}
];

const index = todos.findIndex(todo => todo.id === 3);
console.log(index);

결과 : 2

 

 

📖 C. find

find함수 : findIndex와 비슷하지만, 찾아낸 값이 몇번째인지 알아내는 것이 아닌, 찾아낸 값 자체를 반환한다.

const todos = [
	{
		id : 1,
		text : '자바스크립트 입문',
		done : true
	},
	{
		id : 2,
		text : '함수 배우기',
		done : true
	},
	{
		id : 3,
		text : '객체와 배열 배우기',
		done : true
	},
	{
		id : 4,
		text : '배열 내장함수 배우기',
		done : false
	}
];

const todo = todos.find(todo => todo.id === 3);
console.log(todo);

결과

{id : 3, text : "객체와 배열 배우기", done : true}

 

 

📖 D. filter

filter 함수 : 배열에서 특정 조건을 만족하는 값들만 따로 추출하여 새로운 배열을 만든다.

 

ex) todos 배열에서 done값이 false인 항목들만 따로 추출해서 새로운 배열을 만들어보자!

const todos = [
	{
		id : 1,
		text : '자바스크립트 입문',
		done : true
	},
	{
		id : 2,
		text : '함수 배우기',
		done : true
	},
	{
		id : 3,
		text : '객체와 배열 배우기',
		done : true
	},
	{
		id : 4,
		text : '배열 내장함수 배우기',
		done : false
	}
];

const tasksNotDone todos.filter(todo => todo.done === false);
console.log(tasksNotDone);

결과

[
	{
		id : 4,
		text : '배열 내장 함수 배우기',
		done : false
	}
]
  • filter 함수에 넣은 파라미터는 조건을 검사하는 함수를 넣어주며, 이 함수의 파라미터로 각 원소의 값을 받아오게 된다.

위에 있는 소스를 이와 같이 변경할 수 있다.

const tasksNotDone = todos.filter(todo => !todo.done);

 

 

📖 E. splice

splice : 배열에서 특정 항목을 제거할 때 사용한다.

ex) 30을 지우자

const numbers = [10, 20, 30, 40];
const index = numbers.indexOf(30);
numbers.splice(index, 1);
console,log(numbers);

결과

[10, 20, 40]

splice(p1, p2);

  • p1 : 어떤 인덱스부터 지울지
  • p2 : 그 인덱스부터 몇개를 지울지

 

 

📖 F. slice

slice : 배열을 잘라낼 때 사용, 기존의 배열은 건들이지 않는다.

const numbers = [10, 20, 30, 40];
const sliced = numbers.slice(0, 2); // 0부터 시작해서 2전까지

console.log(sliced); // [10, 20]
console.log(numbers); // [10, 20, 30, 40]

slice에는 두 개의 파라미터를 넣게 된다.

  • 첫 번째 파라미터 : 어디서부터 자를지
  • 두 번째 파라미터 : 어디까지 자를지

 

 

📖 G. shift와 pop

shift : 첫 번째 원소를 배열에서 추출해준다. (추출하는 과정에서 배열에서 해당 원소는 사라진다.)

const numbers = [10, 20, 30, 40];
const value = numbers.shift();
console.log(value);
console.log(numbers);

결과

10
[20, 30, 40]

 

pop : push 의 반대로 생각하면 된다. push는 배열의 맨 마지막에 새 항목을 추가하고, pop은 맨 마지막 항목을 추출한다.

const numbers = [10, 20, 30, 40];
const value = numbers.pop();
console.log(value);
console.log(numbers);

결과

40
[10, 20, 30]

 

 

📖 H. unshift

unshift : shift의 반대, 배열의 맨 앞에 새 원소를 추가한다.

const numbers = [10, 20, 30, 40];
numbers.unshift(5);
console.log(numbers);

결과

[5, 10, 20, 30, 40]

 

 

📖 I. concat

concat : 여러개의 배열을 하나의 배열로 합쳐준다.

const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const concated = arr1.concat(arr2);

console.log(concated);

결과

[1, 2, 3, 4, 5, 6];

concat 함수는 arr1과 arr2에 변화를 주지 않는다.

 

 

📖 J. Join

join : 배열 안의 값들을 문자열 형태로 합쳐준다.

const array = [1, 2, 3, 4, 5];
console.log(array.join()); // 1 2 3 4 5
console.log(array.join(' ')); // 1 2 3 4 5
console.log(array.join(', ')); // 1, 2, 3, 4, 5

 

 

📖 K. reduce

reduce : 유용한 내장 함수, 두 개의 파라미터

  • 첫 번째 파라미터 : accumulatorcurrent를 파라미터로 가져와서 결과를 반환하는 콜백함수
  • 두 번째 파라미터 : reduce 함수에서 사용 할 초깃값

 

💡 참고
accumulator : 누적된 값

 

const numbers = [1, 2, 3, 4, 5];
let sum = numbers.reduce((accumulator, current) => {
	console.log({ accumulator, current});
	return accumulator + current;
}, 0);

console.log(sum);

코드 실행 결과

스크린샷 2022-10-14 오후 9 40 14
  • 배열을 처음부터 끝까지 반복하면서 전달한 콜백 함수가 호출된다.
  • accumulator 값이 0인 이유 : 두 번째 파라미터인 초깃값으로 0을 설정했기 때문이다.

 

✔️ reduce를 사용하여 평균 계산


const numbers = [1, 2, 3, 4, 5];
let sum = numbers.reduce((accumulator, current, index, array) => {
  if (index === array.length - 1) {
    return (accumulator + current) / array.length;
  }
  return accumulator + current;
}, 0);

console.log(sum);

결과 : 3

  • index : 현재 처리하고 있는 항목이 몇 번째인지 가리킨다.
  • array : 현재 처리하고 있는 배열 자신을 의미한다.

ex) 10보다 큰 숫자 갯수 세기

function countBiggerThanTen(numbers) {

/* 구현해보세요 */

	let count = 0;
	
	numbers.forEach(n => {
	
		if (n > 10) {
			count++;
		}
	});

	return count;
}

  

const count = countBiggerThanTen([1, 2, 3, 5, 10, 20, 30, 40, 50, 60]);

console.log(count); // 5

  

export default countBiggerThanTen;

 

 

📚 9. 프로토타입과 클래스

📖 A. 객체 생성자

객체 생성자 : 함수를 통해서 새로운 객체를 만들고 그 안에 넣고 싶은 값 혹은 함수들을 구현할 수 있게 해준다.

function Animal(type, name, sound){
	this.type = type;
	this.name = name;
	this.sound = sound;
	this.say = function(){
		console.log(this.sound);
	};
}

const dog = new Animal('개', '멍멍이', '멍멍');
const cat = new Animal('고양이', '야옹이', '야옹');

dog.say();
cat.say();

결과

멍멍
야옹
  • 객체 생성자를 사용할 때 : 보통 함수의 이름을 대문자로 시작
  • 새로운 객체를 만들 때에는 new 키워드를 앞에 붙여야 한다.

 

💡 참고
프로토타입이란?
같은 객체 생성자 함수를 사용하는 경우, 특정 함수 또는 값을 재사용 할 수 있다.

 

📖 B. 프로토타입

프로토타입 객체 생성자 함수 아래에 .prototype.[원하는키] = 코드를 입력하여 설정할 수 있다.

function Animal(type, name, sound){
	this.type = type;
	this.name = name;
	this.sound = sound;
}

Animal.prototype.say = function(){
	console.log(this.sound);
};
Animal.prototype.sharedValue = 1;

const dog = new Animal('개', '멍멍이', '멍멍');
const cat = new Animal('고양이', '야옹이', '야옹');

dog.say();
cat.say();

console.log(dog.sharedValue);
console.log(cat.sharedValue);

결과

멍멍
야옹
1
1

 

 

📖 C. 객체 생성자 상속받기

function Animal(type, name, sound){
	this.type = type;
	this.name = name;
	this.sound = sound;
}

Animal.prototype.say = function(){
	console.log(this.sound);
}
Animal.prototype.sharedValue = 1;

function Dog(name, sound){
	Animal.call(this, '개', name, sound);
}
Dog.prototype = Animal.prototype;

function Cat(name, sound){
	Amimal.call(this, '고양이', name, sound);
}
Cat.prototype = Animal.prototype;

const dog = new Dog('멍멍이', '멍멍');
const cat = new Cat('야옹이', '야옹');

dog.say();
cat.say();

 

 

📖 D. 클래스

ES6에서부터 class 라는 문법이 추가되었다.
객체 생성자로 구현했던 코드를 조금 더 명확하고, 깔끔하게 구현할 수 있게 해준다.
상속도 훨씬 쉽게 해줄 수 있다.

class Animal{
	constructor(type, name, sound){
		this.type = type;
		this.name = name;
		this.sound = sound;
	}
	say(){
		console.log(this.sound);
	}
}

const dog = new Animal('개', '멍멍이', '멍멍');
const cat = new Animal('고양이', '야옹이', '야옹');

dog.say();
cat.say();

결과

멍멍
야옹
  • 메서드 : 클래스 내부의 함수
  • 이와 같이 메서드를 만들면 자동으로 prototype으로 등록이 된다.

 

class Animal{
	constructor(type, name, sound){
		this.type = type;
		this.name = name;
		this.sound = sound;
	}

	say(){
		console.log(this.sound);
	}
}

class Dog extends Animal{
	constructor(name, sound){
		super('개', name, sound);
	}
}

class Cat extends Animal{
	constructor(name, sound){
		super('고양이', name, sound);
	}
}

const dog = new Dog('멍멍이', '멍멍');
const cat = new Cat('야옹이', '야옹');

dog.say();
cat.say();

결과

멍멍
야옹

 

class Animal{
	constructor(type, name, sound){
	this.type = type;
	this.name = name;
	this.sound = sound;
	}
}

class Dog extends Animal{
	constructor(name, sound){
		super('개', name, sound);
	}
}


class Cat extends Animal{
	constructor(name, sound){
		super('고양이', name, sound);
	}
}

const dog = new Dog('멍멍이', '멍멍');
const dog2 = new Dog('왈왈이', '왈왈');
const cat = new Cat('야옹이', '야옹');
const cat2 = new Cat('냐옹이', '냐옹');

//dog.say();
//dog2.say();
//cat.say();
//cat2.say();

 

✔️ 보기 좋은 클래스

class Food {
  constructor(name) {
    this.name = name;
    this.brands = [];
  }
  addBrand(brand) {
    this.brands.push(brand)
  }
  print() {
    console.log(`${this.name}을/를 파는 음식점들:`)
    console.log(this.brands.join(', '));
  }
}

const pizza = new Food('피자');
pizza.addBrand('피자헛');
pizza.addBrand('도미노 피자');

const chicken = new Food('치킨');
chicken.addBrand('굽네치킨');
chicken.addBrand('BBQ');

pizza.print();
chicken.print();
  • 이와 같이 클래스를 만들어서 사용하면 같은 형태를 지닌 객체들을 만들 때 객체들이 지닌 값과 함수를 보기 좋은 형태로 쉽게 관리할 수 있다.

 

 

profile
"야, (오류 만났어?) 너두 (해결) 할 수 있어"

0개의 댓글

관련 채용 정보