<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
const pet = {
name : '구름',
eat : function(food){
alert(this.name + '은/는 ' + food + '을/를 먹습니다.');
}
}
pet.eat('밥');
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
const student = {
이름: '윤인성',
취미: '악기',
장래희망: '생명공학자'
}
console.log(JSON.stringify(student));
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
const student = {
이름: '윤인성',
취미: '악기',
장래희망: '생명공학자'
}
delete student.장래희망;
console.log(JSON.stringify(student));
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
const pet = {
name : '구름',
eat (food){
alert(this.name + '은/는 ' + food + '을/를 먹습니다.');
}
}
pet.eat('밥');
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
const test = {
a : function() {
console.log(this);
},
b : () => {
console.log(this);
}
}
test.a();
test.b();
</script>
</body>
</html>
문자열을 쉼표를 기준으로 4개씩 새로운 배열을 만들자
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
let input = `
일자,달러,엔,유로
02,1141.8,1097.46,1262.37
03,1148.7,1111.36,1274.65
04,1140.6,1107.81,1266.58
07,1143.4,1099.58,1267.8
08,1141.6,1091.97,1261.07
`;
let arr = input.trim().split('\n').map(a => a.split(','));
console.log(arr);
</script>
</body>
</html>
크롬 콘솔 창에서 빈 배열 하나를 만들고 거기에 sample이라는 속성을 동적으로 하나 만들고 값에 10을 주자. 그런 후에 그 배열에 sample이라는 속성 값을 출력해 보자.
let arr = [];
arr.sample = 10;
arr.sample;
function b() {}
b.sample = 10
b.sample
//10
Array.isArray()const c = 273
c.sample = 10
c.sample
undefined // 속성을 만들 수 있는 것처럼 보이지만 실제로 속성이 만들어지지 않습니다.
자바스크립트는 사용의 편리성을 위해서 기본 자료형의 속성과 메소드를 호출할 때(기본 자료형 뒤에 온점을 찍고 무언가 하려고 하면) 일시적으로 기본 자료형을 객체로 승급시킵니다. 그래서 속성과 메소드를 사용할 수 있는 것입니다.
숫자 전체 객체 전부에 sample이라는 속성을 추가하고 10 이라는 값을 넣자.
그리고 그것을 크롬 콘솔 창에서 확인하자.
//Number은 기본 자료형으로 prototype을 사용해 속성을 추가해야한다.
//안한 예
Number.sample = 20;
(5).sample; //undefined
//prototype 사용 예
Number.prototype.sample = 30;
(3).sample; //30
Number.prototype.power = function (n = 2) {
return this.valueOf() ** n
}
// Number 객체의 power() 메소드를 사용합니다.
const a = 12;
a.power();
a.power(3);
a.power(4);
//Math.pow(); 로도 사용 가능
Math.pow(2, 2); //4
**기호를 사용한다.String.prototype.contain = function (data) {
return this.indexOf(data) >= 0
}
const a = '안녕하세요'
a.contain('하세요'); // true
a.contain('수고'); // false
Array.prototype.contain = function (data) {
return this.indexOf(data) >= 0
}
const b = [273, 32, 103, 57, 52]
b.contain(32); // true
b.contain(123); // false
toFixed() : 소수점 이하 몇 자리까지만 출력하고 싶을 때 사용let number = 123.456789;
let roundedNumber = number.toFixed(2); // 소수점 둘째 자리까지 반올림
console.log(roundedNumber); // 출력: "123.46"
.isFinite() : 양의 무한대, 음의 무한대라면 false >> 비교 연산자로 비교 가능const m = Number('숫자로 변환할 수 없는 경우')
m
//NAN
m === NaN //?
isNaN()함수를 사용해야 한다// 데이터를 생성합니다.
const books = [{
name: '혼자 공부하는 파이썬',
price: 18000,
publisher: '한빛미디어'
}, {
name: 'HTML5 웹 프로그래밍 입문',
price: 26000,
publisher: '한빛아카데미'
}, {
name: '머신러닝 딥러닝 실전 개발 입문',
prie: 30000,
publisher: '위키북스'
}, {
name: '딥러닝을 위한 수학',
price: 25000,
publisher: '위키북스'
}]
풀이
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.15/lodash.min.js">
</script>
<script>
// 데이터를 생성합니다.
const books = [{
name: '혼자 공부하는 파이썬',
price: 18000,
publisher: '한빛미디어'
}, {
name: 'HTML5 웹 프로그래밍 입문',
price: 26000,
publisher: '한빛아카데미'
}, {
name: '머신러닝 딥러닝 실전 개발 입문',
prie: 30000,
publisher: '위키북스'
}, {
name: '딥러닝을 위한 수학',
price: 25000,
publisher: '위키북스'
}]
// 가격으로 정렬한 뒤 출력합니다.
const output = _.sortBy(books, (book) => book.price, 'asc');
console.log(JSON.stringify(output, null,2))
</script>
</head>
<body></body>
</html>
const book ={
name: '혼자 공부하는 파이썬',
price: 18000,
publisher: '한빛미디어'
};
const temp = JSON.stringify(book);
console.log(temp);
{"name":"혼자 공부하는 파이썬","price":18000,"publisher":"한빛미디어"} const object = {
name: '혼자 공부하는 파이썬',
price: 18000,
publisher: '한빛미디어'
}
풀이
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.15/lodash.min.js">
</script>
<script>
const object = {
name: '혼자 공부하는 파이썬',
price: 18000,
publisher: '한빛미디어'
}
// name속성 있는지 체크
if(object.name){
console.log('name 속성이 있습니다.')
} else {
console.log('name 속성이 없습니다.')
}
//author 속성 있는지 체크 >> false값이 들어오지 않는다는 전제 하에
object.author || console.log('author 속성이 없습니다.')
</script>
</head>
<body></body>
</html>
다음 객체에 name 속성이 없다면, 동적으로 name 속성을 주고 그 값을 '제목 미정'이라고 줍니다.
다음 객체에 author 속성이 없다면, 동적으로 author 속성을 주고 그 값을 '저자 미상'라고 줍니다.
그리고 obejct 객체를 출력해봅니다.
const object = {
name: '혼자 공부하는 파이썬',
price: 18000,
publisher: '한빛미디어'
}
풀이
<!DOCTYPE html>
<html>
name에는 원래 존재하던 혼자 공부하는 파이썬이 들어가있고, author속성이 추가되어 저자 미상이라는 값이 들어가 있다.
변수 a, b의 값에 배열 기반의 다중 할당으로 1, 2 의 값으로 초기화 합니다.
4 변수 a, b의 값을 치환합니다.
<!DOCTYPE html>
<html>
<!DOCTYPE html>
<html>
<head>
<title></title>
<script>
let arrayA = [1, 2, 3, 4, 5];
let [a, b, c] = [arrayA[0], arrayA[1], arrayA[2]];
//let [a, b, c] = arrayA; 이렇게 해도 앞에있는 값 먼저 할당
console.log(a, b, c); //1 2 3
</script>
</head>
<body></body>
</html>
다음 object 객체를 이용하여(객체 기반의 다중 할당) name에 object.name을 price에 object.price로 초기화하자.
const object = {
name: '혼자 공부하는 파이썬',
price: 18000,
publisher: '한빛미디어'
}
풀이
<!DOCTYPE html>
<html>
<head>
<title></title>
<script>
// 객체를 생성합니다.
const object = {
name: '혼자 공부하는 파이썬',
price: 18000,
publisher: '한빛미디어'
}
// 객체에서 변수를 추출합니다.
const { name, price } = object // name에 object.name을 price에 object.price를
console.log('# 속성 이름 그대로 꺼내서 출력하기')
console.log(name, price) //혼자 공부하는 파이썬 18000
console.log('')
const { a=name, b=price } = object // a에 object.name을 b에 object.price을
console.log('# 다른 이름으로 속성 꺼내서 출력하기')
console.log(a, b)//혼자 공부하는 파이썬 18000
</script>
</head>
<body></body>
</html>
다음 object 객체를 이용하여(객체 기반의 다중 할당) a에 object.name을 b에 object.price로 초기화하자.
const object = {
name: '혼자 공부하는 파이썬',
price: 18000,
publisher: '한빛미디어'
}
다음의 실행결과를 유추하여 적으시오.
// 사야 하는 물건 목록
const 물건_200301 = ['우유', '식빵']
const 물건_200302 = 물건_200301
물건_200302.push('고구마')
물건_200302.push('토마토')
// 출력
console.log(물건_200301)
console.log(물건_200302)
[...배열, 자료, 자료, 자료] 이렇게 가능 <!DOCTYPE html>
<head>
<title></title>
<script>
const 물건_200301 = ['우유', '식빵']
const 물건_200302 = [...물건_200301]; //전개 연산자 사용해 배열 복사
물건_200302.push('고구마')
물건_200302.push('토마토')
// 출력
console.log(물건_200301) //우유 식빵
console.log(물건_200302) //우유 식빵 고구마 토마토 출력
</script>
</head>
<body></body>
</html>
우유, 식빵 / 고구마, 우유, 식빵, 토마토와 같이 실행 결과가 나오도록 ( )에 적절한 코드를 넣자.
// 사야 하는 물건 목록
const 물건_200301 = ['우유', '식빵']
const 물건_200302 = ( )
// 출력
console.log(물건_200301)
console.log(물건_200302)
풀이
<head>
<title></title>
<script>
const 물건_200301 = ['우유', '식빵']
const 물건_200302 = ['고구마', ...물건_200301, '토마토'];
// 출력
console.log(물건_200301)
console.log(물건_200302)
</script>
</head>
<body></body>
</html>
const a = ['우유', '식빵']
const b = ['고구마', '토마토']
실행결과
(4) ['우유', '식빵', '고구마', '토마토']
(4) ['고구마', '토마토', '우유', '식빵']
풀이
<head>
<title></title>
<script>
const a = ['우유', '식빵']
const b = ['고구마', '토마토']
const a2 = [...a, ...b];
const b2 = [...b, ...a];
console.log(a2);
console.log(b2);
</script>
</head>
<body></body>
</html>
const 구름 = {
이름: '구름',
나이: 6,
종족: '강아지'
}
const 별 = 구름
별.이름 = '별'
별.나이 = 1
console.log(JSON.stringify(구름))
console.log(JSON.stringify(별))
{"이름":"별","나이":1,"종족":"강아지"} 2개의 출력 모두 이렇게 출력 {...객체}<!DOCTYPE html>
<html>
<head>
<title></title>
<script>
const 구름 = {
이름: '구름',
나이: 6,
종족: '강아지'
}
const 별 = {...구름};
별.이름 = '별';
별.나이 = 1;
console.log(JSON.stringify(구름)); //{"이름":"구름","나이":6,"종족":"강아지"}
console.log(JSON.stringify(별)); //{"이름":"별","나이":1,"종족":"강아지"}
</script>
</head>
<body></body>
</html>
다음의 출력결과를 유추하여 적어보자.
const 구름 = {
이름: '구름',
나이: 6,
종족: '강아지'
}
const 별 = {
...구름,
이름: '별', // 기존의 속성 덮어 쓰기
나이: 1, // 기존의 속성 덮어 쓰기
예방접종: true
}
console.log(JSON.stringify(구름))
console.log(JSON.stringify(별))
{"이름":"구름","나이":6,"종족":"강아지"}{"이름":"별","나이":1,"종족":"강아지","예방접종":true} >> 구름의 속성들을 가져와 종족 속성도 존재하는 것이다.다음의 출력결과를 유추하여 적어보자
const 구름 = {
이름: '구름',
나이: 6,
종족: '강아지'
}
const 별 = {
이름: '별',
나이: 1,
예방접종: true,
...구름
}
console.log(JSON.stringify(구름))
console.log(JSON.stringify(별))
{"이름":"구름","나이":6,"종족":"강아지"}{"이름":"구름","나이":6,"예방접종":true,"종족":"강아지"} >> 객체 전개는 순서가 중요하므로 전개를 뒤에서 하니 종족이 뒤에 오는 것을 알 수 있다.<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>상품 설명</title>
</head>
<body>
<h1>상품 설명</h1>
<h2>HTML + CSS + 자바스크립트 웹 표준의 정석</h2>
<p> 한 권으로 끝내는 웹 기본 교과서</p>
<p>코딩 왕초보도 OK! 기초부터 활용까지 완전 정복</p>
<input type="submit" value="주문하기">
<hr>
<p></p>
<script>
const p = document.querySelectorAll('p')[2];
const submit = document.querySelector('input');
const h2 = document.querySelector('h2');
submit.style.cursor = 'pointer';
submit.addEventListener('click', () => {
p.textContent = h2.textContent;
p.style.color = 'blue';
submit.disabled = true;//한번 클릭하면 비활성화
});
</script>
</body>
</html>

구문 오류(syntax error) : 괄호 개수를 잘못 입력하는 등의 오류로 코드가 실행조차 되지 않는 오류
예외(exception) : 문법적 오류를 제외하고 코드 실행 중간에 발생하는 오류 >> 이를 처리하는것이 예외 처리
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
</body>
<script>
document.addEventListener('DOMContentLoaded', () => {
const h1 = document.querySelector('h1')
if (h1) {
h1.textContent = '안녕하세요'
} else {
console.log('h1 태그를 추출할 수 없습니다.')//body에 h1태그가 없기에 출
}
})
</script>
</html>
대부분의 프로그래밍 언어는 배열의 길이를 넘는 위치를 선택할 경우 오류를 발생하지만 자바스크립트는 undefined를 출력하기만 한다.
<!DOCTYPE html>
<html>
<head>
<title></title>
<script>
try {
willExcept.byeBye()
console.log("try 구문의 마지막 줄")
} catch (exception) { //변수 이름이 exception >> 내 맘대로 줘도 됌 보통은 e라고
console.log("catch 구문의 마지막 줄")
}
</script>
</head>
<body>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title></title>
<script>
try {
willExcept.byeBye()
console.log("try 구문의 마지막 줄")
} catch (exception) {
console.log("catch 구문의 마지막 줄")//실행
} finally {
console.log("finally 구문의 마지막 줄")//싱행
}
</script>
</head>
<body>
</body>
</html>
try구문에 들어가면 예외가 발생하던 하지 않던 finally가 실행된다.
어떤 예외가 발생할지
예측하기 힘든 경우가 있다면 고급 예외 처리로 처리해주는 것이 좋다.
throw / return
<!DOCTYPE html>
<html>
<head>
<title></title>
<script>
function test() {
try {
alert('A 위치입니다.')
throw "예외 강제 발생"
} catch (exception) {
alert('B 위치입니다.')
return //test를 호출한 곳으로 돌아간
}
alert('C 위치입니다.')
}
// 함수를 호출합니다.
test()
</script>
</head>
<body>
</body>
</html>
finally
<!DOCTYPE html>
<html>
<head>
<title></title>
<script>
function test() {
try {
alert('A 위치입니다.')
throw "예외 강제 발생"
} catch (exception) {
alert('B 위치입니다.')
return //return이 있어도 finally가 존재해 finally를 실행하고 돌아간다.
} finally {
alert('C 위치입니다.')
}
}
// 함수를 호출합니다.
test()
</script>
</head>
<body>
</body>
</html>
다음 코드 중에서 구문 오류가 발생하는 코드를 고르세요. >> 1번 나머지는 예외처리 가능
①
②
③
④
예외 처리 구문의 조합으로 옳지 않은 것을 고르세요. >> 3번 finally는 마지막
① try {} catch(exception) {}
② try {} finally {}
③ try {} finally {} catch(exception) {}
④ try {} catch(exception) {}
다음 코드 중에서 try catch finally 구문으로 처리할 수 없는 코드를 고르세요. >> 3번 >>> 문법 에러 syntax error
①
②
③
④
4, try catch 예시를 작성하시오
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>예외 처리</title>
</head>
<body>
<script>
try{
const n = 10;
console.log(n() + n());
}catch(e){
console.log('error 발생'); //발생
}
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>예외 처리</title>
</head>
<body>
<script>
try{
const n = 10;
console.log(n() + n());
}catch(e){
console.log('error 발생'); //발생
}finally{
console.log('try를 들어온 순간 finally 구문은 출력될 수 밖에 없쮜~~');//발생
}
</script>
</body>
</html>
function test() {
try {
alert('A 위치입니다.')
throw "예외 강제 발생"
} catch (exception) {
alert('B 위치입니다.')
return
}
alert('C 위치입니다.')
}
// 함수를 호출합니다.
test()
function test() {
try {
alert('A 위치입니다.')
throw "예외 강제 발생"
} catch (exception) {
alert('B 위치입니다.')
return
} finally {
alert('C 위치입니다.')
}
}
// 함수를 호출합니다.
test()
exception object
예외를 강제로 발생시킬 때 throw 키워드 사용
catch에서 예외를 잡는 식별자가 예외 객체다.
예외 객체 : 예외와 관련된 정보를 담은 객체
try catch 구문을 사용할 때 catch의 괄호 안에 입력하는 식별자가 예외 객체(exception object)다. 일반적으로 e나 exception 식별자 사용
예외 객체가 가지고 있는 속성은 브라우저에 따라 조금씩 다르다.
name : 예외 이름
message : 예외 메시지
<!DOCTYPE html>
<html>
<head>
<title></title>
<script>
try {
const array = new Array(999999999999999)
} catch (exception) {
console.log(exception)
console.log()
console.log(`예외 이름: ${exception.name}`)
console.log(`예외 메시지: ${exception.message}`)
}
/*
RangeError: Invalid array length at 8-2-1.html:7:23
8-2-1.html:11 예외 이름: RangeError
8-2-1.html:12 예외 메시지: Invalid array length
*/
</script>
</head>
<body>
</body>
</html>
유틸리티 함수, 클래스를 만들고, 그러한 라이브러리의 함수를 다른 사람들이 활용하는 경우가 있다.
<!DOCTYPE html>
<html>
<head>
<title></title>
<script>
function divide(a, b) {
if (b === 0) {
throw '0으로는 나눌 수 없습니다.'
}
return a / b
}
console.log(divide(10, 2))
console.log(divide(10, 0))
</script>
</head>
<body>
</body>
</html>
throw 구문 사용 가능 형태 2가지
throw 문자열 : 단순하게 예외를 발생
throw new Error(문자열) : 조금 더 자세하게 예외를 발생 >> 파일 이름 과 에러 난 줄 번호까지
throw 문자열
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
function divide(a, b) {
if (b === 0) {
throw '0으로는 나눌 수 없습니다.'
}
return a / b
}
console.log(divide(10, 2))
console.log(divide(10, 0))
</script>
</body>
</html>
throw new Error
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
function divide(a, b) {
if (b === 0) {
throw new Error('0으로는 나눌 수 없습니다.')
}
return a / b
}
console.log(divide(10, 2))
console.log(divide(10, 0))
</script>
</body>
</html>
잘못된 값인데도 정상 실행 코드
<!DOCTYPE html>
<html>
<head>
<title></title>
<script>
function test(object) {
console.log(object.a + object.b)
}
test({})
</script>
</head>
<body>
</body>
</html>
object.a가 undefined로 나오며, object.b도 undefined로 나온다.
object.a가 undefined로 나오며, object.b도 undefined로 나온다. 즉, 정상 실행
사용자에게 함수 잘못 사용 강제 인지 코드
<!DOCTYPE html>
<html>
<head>
<title></title>
<script>
function test(object) {
if (object.a !== undefined && object.b !== undefined) {
console.log(object.a + object.b)
} else {
throw new Error("a 속성과 b 속성을 지정하지 않았습니다.")
}
}
test({})
</script>
</head>
<body>
</body>
</html>
사용자가 코드의 문제점을 인지하고 해결할 수 있다.
예외 객체 : 예외와 관련된 정보를 담은 객체를 의미
throw 구문 : 예외를 강제로 발생시킬 때 사용하는 구문
function sum(x, y){
if(typeof x !== 'number' || typeof y !== 'number'){
throw "숫자를 입력하세요.";
}
return x + y;
}
try{
sum("abc", 1)
} catch(e){
console.log(e);
}
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
try{
let arr = new Array [99999999999999999];
}catch(e){
console.log(e);
console.log(e.name);
console.log(e.meessage);
}
</script>
</body>
</html>

예외를 강제로 발생시킬때 throw 라는 키워드를 쓴다. 2가지 형태가 존재하는데, 이 두 가지 경우의 차이에 대해서 설명해라
throw 문자열 : 문자열만 출력된다.
throw new Error(문자열) : 에러 표시가 뜨고, 문자열과 무슨 파일에서 몇번 째 줄에 에러가 표시되는지 자세한 에러메시지가 뜬다.
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
function divide(a, b) {
if (a === 0 || b === 0) {
throw new Error('0으로는 나눌 수 없습니다.')
}
return a / b
}
console.log(divide(10, 2))
console.log(divide(10, 0))
</script>
</body>
</html>

객체 지향 패러다임이란 객체를 우선적으로 생각해서 프로그램을 만든다는 방법론이다.
클래스 라는 문법으로 객체를 효율적이고 안전하게 만들어 객체 지향 패러다임을 쉽게 프로그래밍에 적용할 수 있도록 도와준다.
추상화 : 복잡한 자료, 모듈, 시스템 등으로부터 핵심적인 개념과 기능을 간추려내는 것을 추상화라고 한다. >> 공통적인 사항들을 가지고 모듈화 또는 재사용
${}구문을 사용해 변수나 표현식을 문자열에 삽입할 수 있다.<!DOCTYPE html>
<html>
<head>
<title></title>
<script>
// 객체를 선언합니다.
const students = []
students.push({ 이름: '구름', 국어: 87, 영어: 98, 수학: 88, 과학: 90})
students.push({ 이름: '별이', 국어: 92, 영어: 98, 수학: 96, 과학: 88})
students.push({ 이름: '겨울', 국어: 76, 영어: 96, 수학: 94, 과학: 86})
students.push({ 이름: '바다', 국어: 98, 영어: 52, 수학: 98, 과학: 92})
// 출력합니다.
let output = '이름\t총점\t평균\n' // 템플릿 리터럴을 사용
for (const s of students) {
const sum = s.국어 + s.영어 + s.수학 + s.과학
const average = sum / 4
output += `${s.이름}\t${sum}점\t${average}점\n`
}
console.log(output)
</script>
</head>
<body>
</body>
</html>

개발자들은 함수를 메소드로써 객체 내부에 넣어서 활용하는 방법을 사용한다.
<!DOCTYPE html>
<html>
<head>
<title></title>
<script>
// 객체를 선언합니다.
const students = []
students.push({ 이름: '구름', 국어: 87, 영어: 98, 수학: 88, 과학: 90})
students.push({ 이름: '별이', 국어: 92, 영어: 98, 수학: 96, 과학: 88})
students.push({ 이름: '겨울', 국어: 76, 영어: 96, 수학: 94, 과학: 86})
students.push({ 이름: '바다', 국어: 98, 영어: 52, 수학: 98, 과학: 92})
// 객체를 처리하는 함수를 선언합니다. > getSumOf함수를 굳이 만들 필요 없이 아래처럼
//function getSumOf (student) {
// return student.국어 + student.영어 + student.수학 + student.과학
//}
// function getAverageOf (student) {
// return getSumOf(student) / 4
// }
// students 배열 내부의 객체 모두에 메소드를 추가합니다. >> 내부에 익명함수 추가
for (const student of students) {
student.getSum = function () {
return this.국어 + this.영어 + this.수학 + this.과학
}
student.getAverage = function () {
return this.getSum() / 4
}
}
// 출력합니다.
let output = '이름\t총점\t평균\n'
for (const s of students) {
output += `${s.이름}\t${getSum(s)}점\t${getAverageOf(s)}점\n`
}
console.log(output)
</script>
</head>
<body>
</body>
</html>

결과값은 1번 예제와 같다.
함수 안에 함수에서는 컴마를 이용해 존재한다.(아래에 클래스에서는 사용하지 않음)
toString : 최상위 클래스인 object클래스의 메소드<!DOCTYPE html>
<html>
<head>
<title></title>
<script>
function createStudent(이름, 국어, 영어, 수학, 과학) {
return {
// 속성을 선언합니다.
이름: 이름,
국어: 국어,
영어: 영어,
수학: 수학,
과학: 과학,
// 메소드를 선언합니다. 사용 중인 코드는 최신 표현
//getSum = function() {} >> 옛날 표현
getSum () {
return this.국어 + this.영어 + this.수학 + this.과학
},
getAverage () {
return this.getSum() / 4
},
toString () {//반드시 this로 접근해야한다.
return `${this.이름}\t${this.getSum()}점\t${this.getAverage()}점\n`
}
}
}
// 객체를 선언합니다.
const students = []
students.push(createStudent('구름', 87, 98, 88, 90))
students.push(createStudent('별이', 92, 98, 96, 88))
students.push(createStudent('겨울', 76, 96, 94, 86))
students.push(createStudent('바다', 98, 52, 98, 92))
// 출력합니다.
let output = '이름\t총점\t평균\n'
for (const s of students) {
output += s.toString()
}
console.log(output)
</script>
</head>
<body>
</body>
</html>
createStudent() 함수를 만들고, 여기에 객체를 만들어 리턴하게 만들었다.
장점
오탈자의 위험이 줄어든다.
코드를 입력하는 양이 크게 줄어든다.
마지막으로 속성과 메소드를 한 함수 내부에서 관리할 수 있으므로 객체를 더 손쉽게 유지보수 할 수 있다.
class: 객체를 만들 때 수많은 지원을 하는 대신 많은 제한을 거는 문법
prototype: 제한을 많이 하지 않지만, 대신 지원도 별로하지 않는 문법 (잘 사용x )
<!DOCTYPE html>
<html>
<head>
<title></title>
<script>
// 클래스를 선언합니다.
class Student {
}
// 학생을 선언합니다.
const student = new Student()
// 학생 리스트를 선언합니다.
const students = [
new Student(),
new Student(),
new Student(),
new Student()
]
</script>
</head>
<body>
</body>
</html>
new 클래스이름 : 객체(인스턴스) 생성
생성자: 클래스를 기반으로 인스턴스를 생성할 때 처음 호출되는 메소드
constructor 키워드를 통해 생성자를 만든다 >> 자바에서는 클래스 이름 >>> 클래스에서만 사용되는 방식 그냥 function만들어서 객체 생성해 넣을 때는 저 키워드 안써도 됌생성자에서는 속성을 추가하는 등의 객체 초기화 처리를 한다.
<!DOCTYPE html>
<html>
<head>
<title></title>
<script>
class Student {
constructor (이름, 국어, 영어, 수학, 과학) {//함수 >>생성자를 호출하면 이 함수가 실행
this.이름 = 이름
this.국어 = 국어
this.영어 = 영어
this.수학 = 수학
this.과학 = 과학
}
}
// 객체를 선언합니다.
const students = []
students.push(new Student('구름', 87, 98, 88, 90))//객체를 만들면서 생성자 호출
students.push(new Student('별이', 92, 98, 96, 88))
students.push(new Student('겨울', 76, 96, 94, 86))
students.push(new Student('바다', 98, 52, 98, 92))
</script>
</head>
<body>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title></title>
<script>
class Student {//클래스
constructor (이름, 국어, 영어, 수학, 과학) {//생성
this.이름 = 이름
this.국어 = 국어
this.영어 = 영어
this.수학 = 수학
this.과학 = 과학
}
getSum () {
return this.국어 + this.영어 + this.수학 + this.과학
}
getAverage () {
return this.getSum() / 4
}
toString () {//최상위 클래스인 object클래스의 메소드
return `${this.이름}\t${this.getSum()}점\t${this.getAverage()}점\n`
}
/*
처음 코드를 입력할 때, 메소드 사이에 쉼표를 넣는 실수를 하는 경우가 있는데,
쉼표가 있으면 안 됩니다.
*/
}
// 객체를 선언합니다.
const students = []
students.push(new Student('구름', 87, 98, 88, 90))
students.push(new Student('별이', 92, 98, 96, 88))
students.push(new Student('겨울', 76, 96, 94, 86))
students.push(new Student('바다', 98, 52, 98, 92))
//출력합니다.
let output = '이름\t총점\t평균\n'
for (const s of students) {
output += s.toString()
}
console.log(output)
</script>
</head>
<body>
</body>
</html>
이름 총점 평균
구름 363점 90.75점
별이 374점 93.5점
겨울 352점 88점
바다 340점 85점
// 객체를 선언합니다.
const students = []
students.push({ 이름: '구름', 국어: 87, 영어: 98, 수학: 88, 과학: 90})
students.push({ 이름: '별이', 국어: 92, 영어: 98, 수학: 96, 과학: 88})
students.push({ 이름: '겨울', 국어: 76, 영어: 96, 수학: 94, 과학: 86})
students.push({ 이름: '바다', 국어: 98, 영어: 52, 수학: 98, 과학: 92})
// 코드 추가
// 출력합니다.
let output = '이름\t총점\t평균\n'
for (const s of students) {
output += `${s.이름}\t${s.getSum()}점\t${s.getAverage()}점\n`
}
console.log(output)
풀이
<!DOCTYPE html>
<html>
<head>
<title></title>
<script>
// 객체를 선언합니다.
const students = []
students.push({ 이름: '구름', 국어: 87, 영어: 98, 수학: 88, 과학: 90})
students.push({ 이름: '별이', 국어: 92, 영어: 98, 수학: 96, 과학: 88})
students.push({ 이름: '겨울', 국어: 76, 영어: 96, 수학: 94, 과학: 86})
students.push({ 이름: '바다', 국어: 98, 영어: 52, 수학: 98, 과학: 92})
// 코드 추가
for(const student of students){
student.getSum = function(){
return this.국어 + this.영어 + this.수학 + this.과학;
}
student.getAverage = function() {
return this.getSum() / 4;
}
}
// 출력합니다.
let output = '이름\t총점\t평균\n'
for (const s of students) {
output += `${s.이름}\t${s.getSum()}점\t${s.getAverage()}점\n`
}
console.log(output)
</script>
</head>
<body>
</body>
</html>
객체 안에 메소드가 존재해야 하기 때문에 for~of문을 이용해 students배열 안에 존재하는 객체들을 꺼내서 메소드를 추가해준다.
이름 총점 평균
구름 363점 90.75점
별이 374점 93.5점
겨울 352점 88점
바다 340점 85점
// 객체를 선언합니다.
const students = []
students.push(createStudent('구름', 87, 98, 88, 90))
students.push(createStudent('별이', 92, 98, 96, 88))
students.push(createStudent('겨울', 76, 96, 94, 86))
students.push(createStudent('바다', 98, 52, 98, 92))
// 출력합니다.
let output = '이름\t총점\t평균\n'
for (const s of students) {
output += s.toString()
}
console.log(output)
풀이
<!DOCTYPE html>
<html>
<head>
<title></title>
<script>
function createStudent(이름, 국어, 영어, 수학, 과학){
return{
이름 : 이름, 국어 : 국어, 영어: 영어, 수학: 수학, 과학: 과학, //속성 지정
getSum(){
return this.국어 + this.영어 + this.수학 + this.과학;
},
getAverage(){
return this.getSum() / 4;
},
toString(){
return `${this.이름}\t${this.getSum()}점\t${this.getAverage()}점\n`;
}
}
}
// 객체를 선언합니다.
const students = []
students.push(createStudent('구름', 87, 98, 88, 90))
students.push(createStudent('별이', 92, 98, 96, 88))
students.push(createStudent('겨울', 76, 96, 94, 86))
students.push(createStudent('바다', 98, 52, 98, 92))
// 출력합니다.
let output = '이름\t총점\t평균\n'
for (const s of students) {
output += s.toString()
}
console.log(output)
</script>
</head>
<body>
</body>
</html>
// 객체를 선언합니다.
const students = []
students.push(new Student('구름', 87, 98, 88, 90))
students.push(new Student('별이', 92, 98, 96, 88))
students.push(new Student('겨울', 76, 96, 94, 86))
students.push(new Student('바다', 98, 52, 98, 92))
풀이
<!DOCTYPE html>
<html>
<head>
<title></title>
<script>
// 객체를 선언합니다.
const students = []
students.push(new Student('구름', 87, 98, 88, 90))
students.push(new Student('별이', 92, 98, 96, 88))
students.push(new Student('겨울', 76, 96, 94, 86))
students.push(new Student('바다', 98, 52, 98, 92))
class Student{
constructor(이름, 국어, 영어, 수학, 과학){
this.이름= 이름;
this.국어 = 국어;
this.영어 = 영어;
this.수학 = 수학;
this.과학 = 과학;
}
}
</script>
</head>
<body>
</body>
</html>
이름 총점 평균
구름 363점 90.75점
별이 374점 93.5점
겨울 352점 88점
바다 340점 85점
// 객체를 선언합니다.
const students = []
students.push(new Student('구름', 87, 98, 88, 90))
students.push(new Student('별이', 92, 98, 96, 88))
students.push(new Student('겨울', 76, 96, 94, 86))
students.push(new Student('바다', 98, 52, 98, 92))
//출력합니다.
let output = '이름\t총점\t평균\n'
for (const s of students) {
output += s.toString()
}
console.log(output)
풀이
<!DOCTYPE html>
<html>
<head>
<title></title>
<script>
class Student{
constructor(이름, 국어, 영어, 수학, 과학){
this.이름= 이름;
this.국어 = 국어;
this.영어 = 영어;
this.수학 = 수학;
this.과학 = 과학;
}
getSum(){
return this.국어 + this.영어 + this.수학 + this.과학;
}
getAverage(){
return this.getSum() / 4;
}
toString(){
return `${this.이름}\t${this.getSum()}점\t${this.getAverage()}점\n`;
}
}
// 객체를 선언합니다.
const students = []
students.push(new Student('구름', 87, 98, 88, 90))
students.push(new Student('별이', 92, 98, 96, 88))
students.push(new Student('겨울', 76, 96, 94, 86))
students.push(new Student('바다', 98, 52, 98, 92))
//출력합니다.
let output = '이름\t총점\t평균\n'
for (const s of students) {
output += s.toString()
}
console.log(output);
</script>
</head>
<body>
</body>
</html>
this키워드를 사용하는 이유는 해당 메소드가 속한 객체의 속성을 참조하기 위함이다.
class Student로 묶여 있지만, 클래스로 정의된 메소드는 해당 클래스의 인스턴스에 속한 것이기 때문에 클래스 내에서 this키워드를 사용하여 현재 인스턴스의 속성에 접근해야한다.
각 인스턴스는 클래스의 구조를 공유하지만, 실제 데이터는 독립적으로 유지되기 때문에 해당 인스턴스의 값을 참조하기 위해 this를 사용해야한다.
<!DOCTYPE html>
<html>
<head>
<title></title>
<script>
class Rectangle {
constructor (width, height) {
this.width = width
this.height = height
}
// 사각형의 둘레를 구하는 메소드
getPerimeter () {
return 2 * (this.width + this.height)
}
// 사각형의 넓이를 구하는 메소드
getArea () {
return this.width * this.height
}
}
const rectangle = new Rectangle(10, 20)
console.log(`사각형의 둘레: ${rectangle.getPerimeter()}`)
console.log(`사각형의 넓이: ${rectangle.getArea()}`)
</script>
</head>
<body>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title></title>
<script>
class Rectangle {
constructor (width, height) {
this.width = width
this.height = height
}
// 사각형의 둘레를 구하는 메소드
getPerimeter () {
return 2 * (this.width + this.height)
}
// 사각형의 넓이를 구하는 메소드
getArea () {
return this.width * this.height
}
}
// 정사각형 클래스
class Square {
constructor (length) {
this.length = length
}
// 정사각형의 둘레를 구하는 메소드
getPerimeter () {
return 4 * this.length
}
// 정사각형의 넓이를 구하는 메소드
getArea () {
return this.length * this.length
}
}
// 클래스 사용하기
const square = new Square(10)
console.log(`정사각형의 둘레: ${square.getPerimeter()}`)
console.log(`정사각형의 넓이: ${square.getArea()}`)
</script>
</head>
<body>
</body>
</html>
자식 클래스 이름 extends 상속받을 부모클래스 이름 : 이런 형태로 상속 선언
<!DOCTYPE html>
<html>
<head>
<title></title>
<script>
// 사각형 클래스
class Rectangle {
constructor (width, height) {
this.width = width
this.height = height
}
// 사각형의 둘레를 구하는 메소드
getPerimeter () {
return 2 * (this.width + this.height)
}
// 사각형의 넓이를 구하는 메소드
getArea () {
return this.width * this.height
}
}
// 정사각형 클래스
class Square extends Rectangle {
constructor (length) {
super(length, length) // 부모의 생성자 함수를 호출하는 클래스
}
}
// 클래스 사용하기
const square = new Square(10)
console.log(`정사각형의 둘레: ${square.getPerimeter()}`)
console.log(`정사각형의 넓이: ${square.getArea()}`)
/*
getPerimeter() 메소드와 getArea() 메소드를 선언하지 않았지만,
상속받았으므로 사용할 수 있습니다.
*/
</script>
</head>
<body>
</body>
</html>
만약 사용자가 잘못된 값으로 객체를 생성한다면, 해당 객체의 잘못된 값으로 변경하는 것을 막을 수 없기 때문에 안전성을 확보하기 위해 private속성과 메소드 문법이 나왔다.
# : private을 사용하고 싶다면 속성과 메소드 이름 앞에 #을 붙이기만 하면된다.
주의 : private 속성을 사용하기 전에 외부에 private속성으로 사용하겠다고 선언해야 한다.
<!DOCTYPE html>
<html>
<head>
<title></title>
<script>
// 사각형 클래스
class Square {
#length // 이 위치에 해당 속성을 private 속성으로 사용하겠다고 미리 선언합니다.
constructor (length) {
if (length <= 0) {
throw '길이는 0보다 커야 합니다.'
}
this.#length = length
}
getPerimeter () { return 4 * this.#length }
getArea () { return this.#length * this.#length }
}
// 클래스 사용하기
const square = new Square(10)
console.log(`정사각형의 둘레: ${square.getPerimeter()}`)
console.log(`정사각형의 넓이: ${square.getArea()}`)
</script>
</head>
<body>
</body>
</html>
private 속성으로 변경하면 클래스 외부에서는 해당 속성에 접근할 수 없다.
만약 -10을 넣었다면, throw를 통해 예외를 발생시켜 -10이라는 값은 생성자에서 거부되고 #length는 설정되지 않아 undefined일 것이다.
class 밖에서 private속성 선언
<!DOCTYPE html>
<html>
<head>
<title></title>
<script>
// 사각형 클래스
class Square {
#length
constructor (length) {
if (length <= 0) {
throw '길이는 0보다 커야 합니다.'
}
this.#length = length
}
getPerimeter () { return 4 * this.#length }
getArea () { return this.#length * this.#length }
}
// 클래스 사용하기
const square = new Square(10)
square.#length = -10 //error
console.log(`정사각형의 둘레: ${square.getPerimeter()}`)
console.log(`정사각형의 넓이: ${square.getArea()}`)
</script>
</head>
<body>
</body>
</html>
자바스크립트에서는 getter, setter메소드가 따로 존재한다.
get 메서드 이름() : 속성 값을 확인할 때 사용하는 메소드를 게터(getter)
set 메서드 이름() : 속성에 값을 지정할 때 사용하는 메소드를 세터(setter)
자바스크립트에서는 클래스의 getter, setter메서드에 대한 호출을 직접적으로 생략할 수 있다. 일반적인 속성처럼 접근 가능 >> get, set속성은 클래스 외부에서 직접적으로 접근할 수 없다.
<!DOCTYPE html>
<html>
<head>
<title></title>
<script>
// 정사각형 클래스
class Square {
#length
/*
this.length에 값을 지정하면,
set length(length) 메소드 부분이 호출된다.
*/
constructor (length) {
this.length = length
// this.#length = length
}
get length () {
return this.#length
}
get perimeter () {
return this.#length * 4
}
get area () {
return this.#length * this.#length
}
set length (length) {
if (length <= 0) {
throw '길이는 0보다 커야 합니다.'
}
this.#length = length
}
}
// 클래스 사용하기
const squareA = new Square(10)
console.log(`한 변의 길이: ${squareA.length}`)//get length 호출
console.log(`둘레: ${squareA.perimeter}`) //get perimeter 호출
console.log(`넓이: ${squareA.area}`)//get area 호
// 예외 발생시키기
const squareB = new Square(-10)
</script>
</head>
<body>
</body>
</html>
클래스이름.속성 >> static선언 할 때는 속성 앞에 static 선언하면 된다.클래스이름.메소드() >> static선언 할 때는 메소드 앞에 static 선언하면 된다. (띄어쓰기 해야함)<!DOCTYPE html>
<html>
<head>
<title></title>
<script>
class Square {
#length
static #conuter = 0 // private 특성과 static 특성은 한꺼번에 적용할 수도 있다.
static get counter () {
return Square.#conuter
}
constructor (length) {
this.length = length //set length()호출
Square.#conuter += 1
}
static perimeterOf (length) {
return length * 4
}
static areaOf (length) {
return length * length
}
get length () { return this.#length }
get perimeter () { return this.#length * 4 }
get area () { return this.#length * this.#length }
set length (length) {
if (length < 0) {
throw '길이는 0보다 커야 합니다.'
}
this.#length = length
}
}
// static 속성 사용하기
const squareA = new Square(10)
const squareB = new Square(20)
const squareC = new Square(30)
console.log(`지금까지 생성된 Square 인스턴스는 ${Square.counter}개입니다.`)//static get counter()호출
// static 메소드 사용하기 >> 클래스 이름으로 호출
console.log(`한 변의 길이가 20인 정사각형의 둘레는 ${Square.perimeterOf(20)}입니다.`)
console.log(`한 변의 길이가 30인 정사각형의 둘레는 ${Square.areaOf(30)}입니다.`)
</script>
</head>
<body>
</body>
</html>
- 어떤 속성과 함수가 클래스 내부에 귀속되어 있다는 것을 명시적으로 나타낼 수 있다.
- 어떤 속성과 함수가 클래스 내부에 귀속되어 있다는 것을 명시적으로 나타낼 수 있다.
오버라이드(override) : 부모 클래스가 갖고 있는 함수를 자식에서 다시 선언해서 덮은 것
<!DOCTYPE html>
<html>
<head>
<title></title>
<script>
// 클래스를 선언합니다.
class LifeCycle {
call () {
this.a()
this.b()
this.c()
}
a () { console.log('a() 메소드를 호출합니다.')}
b () { console.log('b() 메소드를 호출합니다.')}
c () { console.log('c() 메소드를 호출합니다.')}
}
class Child extends LifeCycle {
a () {
console.log('자식의 a() 메소드입니다.')
}
}
// 인스턴스를 생성해 부모 클래스 메소드 사용
new Child().call()
</script>
</head>
<body>
</body>
</html>
자식의 a() 메소드입니다. b() 메소드를 호출합니다.c() 메소드를 호출합니다. >> 최종적으로 오버라이딩된거 출력
<!DOCTYPE html>
<html>
<head>
<title></title>
<script>
// 클래스를 선언합니다.
class LifeCycle {
call () {
this.a()
this.b()
this.c()
}
a () { console.log('a() 메소드를 호출합니다.')}
b () { console.log('b() 메소드를 호출합니다.')}
c () { console.log('c() 메소드를 호출합니다.')}
}
class Child extends LifeCycle {
a () {
super.a()
console.log('자식의 a() 메소드입니다.')
}
}
// 인스턴스를 생성합니다.
new Child().call()
</script>
</head>
<body>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title></title>
<script>
class Pet {
constructor (name, age) {
this.name = name
this.age = age
}
toString () {
return `이름: ${this.name}\n나이: ${this.age}살`
}
}
const pet = new Pet('구름', 6)
alert(pet)
console.log(pet + '')
</script>
</head>
<body>
</body>
</html>
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
class Rectangle {
constructor(width, height) {
this.width = width;
this.height = height;
}
perimeter() {
return 2 * (this.width + this.height);
}
area() {
return this.width * this.height;
}
}
const rec = new Rectangle(2, 3);
console.log(`둘레 : ${rec.perimeter()}`);//10
console.log(`넓이 : ${rec.area()}`);//6
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
class Rectangle {
constructor(width, height) {
this.width = width;
this.height = height;
}
perimeter() {
return 2 * (this.width + this.height);
}
area() {
return this.width * this.height;
}
}
class Square extends Rectangle{
constructor(length){
super(length,length);
}
}
const sq = new Square(10);
console.log(`둘레 : ${sq.perimeter()}`);//40
console.log(`넓이 : ${sq.area()}`);//100
</script>
</body>
</html>
// 정사각형 클래스
class Square {
constructor (length) {
// 예외발생 코드 추가
this.length = length
}
getPerimeter () { return 4 * this.length }
getArea () { return this.length * this.length }
}
// 클래스 사용하기
const square = new Square(-10)
console.log(`정사각형의 둘레: ${square.getPerimeter()}`)
console.log(`정사각형의 넓이: ${square.getArea()}`)
풀이
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
// 정사각형 클래스
class Square {
constructor (length) {
// 예외발생 코드 추가
if(length < 0){
throw '길이가 0 이상이여야 합니다.';
}
this.length = length
}
getPerimeter () { return 4 * this.length }
getArea () { return this.length * this.length }
}
// 클래스 사용하기
const square = new Square(-10); //Example.html:17 Uncaught 길이가 0 이상이여야 합니다.
console.log(`정사각형의 둘레: ${square.getPerimeter()}`)
console.log(`정사각형의 넓이: ${square.getArea()}`)
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
// 정사각형 클래스
class Square {
#length;
constructor(length) {
// 예외발생 코드 추가
if (length < 0) {
throw '길이가 0 이상이여야 합니다.';
}
this.length = length
}
getPerimeter() { return 4 * this.length }
getArea() { return this.length * this.length }
}
// 클래스 사용하기
const square = new Square(10);
console.log(`정사각형의 둘레: ${square.getPerimeter()}`);//40
console.log(`정사각형의 넓이: ${square.getArea()}`);//100
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
// 정사각형 클래스
class Square {
#length;
constructor(length) {
this.length = length;//값을 지정하면 set메소드 호출
}
get length(){return this.#length;}
get perimeter() { return 4 * this.#length }
get area() { return this.length * this.#length }
set length(length){
if (length <= 0) {
throw '길이가 0 이상이여야 합니다.';
}
this.#length = length;
}
}
// 클래스 사용하기
const square = new Square(10);
const exSq = new Square(-10);//예외 발생
console.log(`정사각형 변의 길이: ${square.length}`);//10
console.log(`정사각형의 둘레: ${square.perimeter}`);//40
console.log(`정사각형의 넓이: ${square.area}`);//100
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
class Square {
#length;
static #counter = 0;
constructor(length) {
this.length = length;
Square.#counter++;
}
static get counter() {
return Square.#counter; //this.counter도 가능
}
static perimeterOf(length) {
return 4 * length;
}
static areaOf(length) {
return length * length
}
set length(length) {//setter 메소드
if (length <= 0) {
throw '길이는 0 이상이여야 합니다.';
}
this.#length = length;
}
get length() { return this.#length }
get perimeter() { return this.#length * 4 }
get area() { return this.#length * this.#length }
}
// static 속성 사용하기
const squareA = new Square(10);
const squareB = new Square(20);
const squareC = new Square(30);
console.log(`지금까지 생성된 Square 인스턴스는 ${Square.counter}개입니다.`)//3개
//static get counter()호출
// static 메소드 사용하기 >> 클래스 이름으로 호출
console.log(`한 변의 길이가 20인 정사각형의 둘레는 ${Square.perimeterOf(20)}입니다.`)//80
console.log(`한 변의 길이가 30인 정사각형의 둘레는 ${Square.areaOf(30)}입니다.`)//900
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title></title>
<script>
// 클래스를 선언합니다.
class LifeCycle {
call () {
this.a()
this.b()
}
a () { console.log('a() 메소드를 호출합니다.')}
b () { console.log('b() 메소드를 호출합니다.')}
}
class Child extends LifeCycle {
a () {
super.a()
console.log('자식의 a() 메소드입니다.')
}
}
// 인스턴스를 생성합니다.
new Child().call()
</script>
</head>
<body>
</body>
</html>
// 클래스를 선언합니다.
class LifeCycle {
call () {
this.a()
this.b()
this.c()
}
a () { console.log('a() 메소드를 호출합니다.')}
b () { console.log('b() 메소드를 호출합니다.')}
c () { console.log('c() 메소드를 호출합니다.')}
}
class Child extends LifeCycle {
a () {
console.log('자식의 a() 메소드입니다.')
}
}
// 인스턴스를 생성합니다.
new Child().call()
// 클래스를 선언합니다.
class LifeCycle {
call () {
this.a()
this.b()
this.c()
}
a () { console.log('a() 메소드를 호출합니다.')}
b () { console.log('b() 메소드를 호출합니다.')}
c () { console.log('c() 메소드를 호출합니다.')}
}
class Child extends LifeCycle {
a () {
super.a()
console.log('자식의 a() 메소드입니다.')
}
}
// 인스턴스를 생성합니다.
new Child().call()
<!DOCTYPE html>
<html>
<head>
<title></title>
<script>
class Example{
constructor(num){
this.num = num;
}
toString(){
return `당신이 입력한 숫자는 ${this.num} 입니다`;
}
}
// 인스턴스를 생성합니다.
const ex = new Example(30);
console.log(ex.toString()); //당신이 입력한 숫자는 30 입니다
</script>
</head>
<body>
</body>
</html>
모질라 사의 자바스크립트 개발자였던 존 레식(John Resig)이 자바스크립트를 이용해 만든 라이브러리 언어 >> javascript로 만들어진 다양한 함수들의 집합
제이쿼리 다운로드 : https://jquery.com/download/
cdn 방식 : https://code.jquery.com/
<head>
<meta charset="UTF-8">
<title> 선택자 </title>
<script src="js/jquery.js"></script>
<script>
$(function(){//html이 모두 로드된
$("*").css("border","1px solid blue"); //전체에 css실
});
</script>
</head>
<body>
<h1>제이쿼리</h1>
<h2>선택자</h2>
<h3>직접 선택자</h3>
</body>
$("#아이디명")
<head>
<meta charset="UTF-8">
<title> 선택자 </title>
<script src="js/jquery.js"></script>
<script>
$(function(){
$("#tit").css("background-color","#ff0")
.css("border", "2px solid #f00");
});
</script>
</head>
<body>
<h1>제이쿼리</h1>
<h2 id="tit">선택자</h2>
<h3>직접 선택자</h3>
</body>
$(".클래스명")
<head>
<meta charset="UTF-8">
<title> 선택자 </title>
<script src="js/jquery.js"></script>
<script>
$(function(){
$(".tit").css("background-color","#ff0")
.css("border", "2px dashed #f00");
});
</script>
</head>
<body>
<h1>제이쿼리</h1>
<h2 class="tit">선택자</h2>
<h3>직접 선택자</h3>
</body>
$("요소명")
<head>
<meta charset="UTF-8">
<title> 선택자 </title>
<script src="js/jquery.js"></script>
<script>
$(function(){
$("h2").css("background-color","#0ff")
.css("border", "2px dashed #f00");
});
</script>
</head>
<body>
<h1>제이쿼리</h1>
<h2>선택자</h2>
<h3>직접 선택자</h3>
</body>
$("요소선택1, 요소선택2, 요소선택3,...요소선택n");<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title> 선택자 </title>
<script src="js/jquery.js"></script>
<script>
$(function(){
$("h1, #tit3").css("background-color","#0ff")
.css("border", "2px dashed #f00");
});
</script>
</head>
<body>
<h1>제이쿼리</h1>
<h2>선택자</h2>
<h3 id="tit3">직접 선택자</h3>
<h3>인접 선택자</h3>
</body>
</html>
$("요소명#id값") / $("요소명.class값")<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title> 선택자 </title>
<script src="js/jquery.js"></script>
<script>
$(function(){ //css를 하나씩 주는 방법 > 메소드 체이닝 형태
$("h1.tit").css("background-color","#0ff") //h1태그에 클래스가 tit인
.css("border", "2px dashed #f00");
});
</script>
</head>
<body>
<h1 class="tit">제이쿼리</h1>
<h2>선택자</h2>
<h3 class="tit">직접 선택자</h3>
</body>
</html>
$("요소 선택").parent();<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title> 선택자 </title>
<script src="js/jquery.js"></script>
<script>
$(function(){
$("#list_1").parent() //class가 list_1인 부모 요소를 선택
.css("border", "2px dashed #f00");
});
</script>
</head>
<body>
<h1>인접 관계 선택자</h1>
<ul id="wrap">
<li>리스트1
<ul>
<li id="list_1">리스트1-1</li>
<li>리스트1-2</li>
</ul>
</li>
<li>리스트2</li>
<li>리스트3</li>
</ul>
</body>
</html>
$("기준요소선택1 요소선택2")<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title> 선택자 </title>
<script src="js/jquery.js"></script>
<script>
$(function(){
$("#wrap h1")//후손
.css({ //css를 객체 형태로 주는 방법도 있다. 이게 더 편리하긴 할듯
"background-color":"yellow",
"border":"2px dashed #f00"
});
});
</script>
</head>
<body>
<div id="wrap">
<h1>인접 관계 선택자</h1>
<p>내용1</p>
<section>
<h1>하위 요소 선택자</h1>
<p>내용2</p>
</section>
</div>
</body>
</html>
$("요소선택 > 자식요소선택")$("요소선택").children("자식요소선택") >> 1번, 2번 모두 선택한 요소를 기준으로 지정한 자식 요소만 선택$("요소선택").children() >> 선택한 요소를 기준으로 모든 자식 요소를 선택<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title> 선택자 </title>
<script src="js/jquery.js"></script>
<script>
$(function(){
$("#wrap > h1").css("border","2px dashed #f00");
$("#wrap > section").children( )
.css({
"background-color":"yellow",
"border":"2px solid #f00"
});
});
</script>
</head>
<body>
<div id="wrap">
<h1>인접 관계 선택자</h1>
<p>내용1</p>
<section>
<h1>자식 요소 선택자</h1>
<p>내용2</p>
</section>
</div>
</body>
</html>
$("요소선택").prev() : 선택한 요소를 기준으로 이전에 오는 형제 요소만 선택 $("요소선택").next() : 선택한 요소를 기준으로 다음에 오는 형제 요소만 선택$("요소선택1 + 요소선택2") : 선택한 요소를(요소선택1) 기준으로 바로 다음에 오는 선택한 요소(요소선택2)만 선택<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title> 선택자 </title>
<script src="js/jquery.js"></script>
<script>
$(function(){
var style_1 = {
"background-color":"#0ff",
"border":"2px solid #f00"
}
var style_2 = {
"background-color":"#ff0",
"border":"2px dashed #f00"
}
$(".txt").prev()
.css(style_1);
$(".txt + p").css(style_2);
$(".txt").next().next()
.css(style_2);
});
</script>
</head>
<body>
<div id="wrap">
<h1>인접 관계 선택자</h1>
<p>내용1</p>
<p class="txt">내용2</p>
<p>내용3</p>
<p>내용4</p>
</div>
</body>
</html>
$("요소선택").prevAll()$("요소선택").nextAll()<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title> 선택자 </title>
<script src="js/jquery.js"></script>
<script>
$(function(){
var style_1 = {
"background-color":"#0ff",
"border":"2px solid #f00"
}
var style_2 = {
"background-color":"#ff0",
"border":"2px dashed #f00"
}
$(".txt").prevAll( )
.css(style_1);
$(".txt").nextAll( )
.css(style_2);
});
</script>
</head>
<body>
<div id="wrap">
<h1>인접 관계 선택자</h1>
<p>내용1</p>
<p class="txt">내용2</p>
<p>내용3</p>
<p>내용4</p>
</div>
</body>
</html>
$("요소선택").siblings();<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title> 선택자 </title>
<script src="js/jquery.js"></script>
<script>
$(function(){
var style_1 = {
"background-color":"#0ff",
"border":"2px solid #f00"
}
$(".txt").siblings( )
.css(style_1);
});
</script>
</head>
<body>
<div id="wrap">
<h1>인접 관계 선택자</h1>
<p>내용1</p>
<p class="txt">내용2</p>
<p>내용3</p>
<p>내용4</p>
</div>
</body>
</html>
$("요소선택").prevUntil("범위제한요소선택") : 선택한 요소를 기준으로 범위 제한 요소까지 전체 형 요소를 선택$("요소선택").nextUntil("범위제한요소선택") : 선택한 요소를 기준으로 범위 제한 요소까지 전체 동생 요소를 선택<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title> 선택자 </title>
<script src="js/jquery.js"></script>
<script>
$(function(){
var style_1 = {
"background-color":"#0ff",
"border":"2px solid #f00"
}
$(".txt3").prevUntil(".title")
.css(style_1);
$(".txt3").nextUntil(".txt6")
.css(style_1);
});
</script>
</head>
<body>
<div id="wrap">
<h1 class="title">선택자</h1>
<p>내용1</p>
<p>내용2</p>
<p class="txt3">내용3</p>
<p>내용4</p>
<p>내용5</p>
<p class="txt6">내용6</p>
</div>
</body>
</html>
$("요소선택").parents() : 선택한 요소를 기준으로 상위 요소를 모두 선택$("요소선택").parents("요소선택") : 선택한 요소를 기준으로 상위 요소 중 선택한 요소만 선택합니다.<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title> 선택자 </title>
<script src="js/jquery.js"></script>
<script>
$(function(){
$(".txt1").parents()
.css({
"border":"2px dashed #00f"
});
$(".txt2").parents("div")
.css({
"border":"2px solid #f00"
});
});
</script>
</head>
<body>
<h1 class="title">선택자</h1>
<section>
<div>
<p class="txt1">내용</p>
</div>
</section>
<section>
<div>
<p class="txt2">내용</p>
</div>
</section>
</body>
</html>
$("요소선택").closest("요소선택")<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title> 선택자 </title>
<script src="js/jquery.js"></script>
<script>
$(function(){
$(".txt1").closest("div")
.css({
"border":"2px solid #f00"
});
});
</script>
</head>
<body>
<h1 class="title">선택자</h1>
<div>
<div> <!--이 부분 closest 해당-->
<p class="txt1">내용</p>
</div>
</div>
</body>
</html>
$("요소선택").css("속성명1", "값1").css("속성명2", "값2");$("요소 선택").css({"속성명1" : "값1", "속성명2" : "값2" ... "속성명n":"값n"});<!DOCTYPE html>
<html lang="ko"
<head>
<meta charset="UTF-8">
<title> 선택자 </title>
<script src="js/jquery.js"></script>
<script>
$(function () {
$("#txt").css("color", "red");
})
</script>
</head>
<body>
<p id="txt">내용</p>
</body>
</html>
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title> 선택자 </title>
<script src="js/jquery.js"></script>
<script>
$(function () {
$("*").css("border", "1px solid blue");
});
</script>
</head>
<body>
<h1>제이쿼리</h1>
<h2>선택자</h2>
<h3>직접 선택자</h3>
</body>
</html>

<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title> 선택자 </title>
<script src="js/jquery.js"></script>
<script>
$(function () {
$("#tit").css({
"background": "#ff0", "border": "2px solid #f00"
});
});
</script>
</head>
<body>
<h1>제이쿼리</h1>
<h2 id="tit">선택자</h2>
<h3>직접 선택자</h3>
</body>
</html>

<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title> 선택자 </title>
<script src="js/jquery.js"></script>
<script>
$(function () {
$(".tit").css({
"backgroundColor": "#ff0", "border": "2px dashed #f00"
});
});
</script>
</head>
<body>
<h1>제이쿼리</h1>
<h2 class="tit">선택자</h2>
<h3>직접 선택자</h3>
</body>
</html>

<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title> 선택자 </title>
<script src="js/jquery.js"></script>
<script>
$(function () {
$("h2").css("background-color", "#0ff").css("border", "2px dashed #f00");
});
</script>
</head>
<body>
<h1>제이쿼리</h1>
<h2>선택자</h2>
<h3>직접 선택자</h3>
</body>
</html>

<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title> 선택자 </title>
<script src="js/jquery.js"></script>
<script>
$(function () {
$("h3#tit3").css("background-color", "#0ff").css("border", "2px dashed #f00");
});
</script>
</head>
<body>
<h1>제이쿼리</h1>
<h2>선택자</h2>
<h3 id="tit3">직접 선택자</h3>
<h3>인접 선택자</h3>
</body>
</html>

<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title> 선택자 </title>
<script src="js/jquery.js"></script>
<script>
$(function () {
$("h3.tit").css("background-color", "#0ff").css("border", "2px dashed #f00");
});
</script>
</head>
<body>
<h1 class="tit">제이쿼리</h1>
<h2>선택자</h2>
<h3 class="tit">직접 선택자</h3>
</body>
</html>

<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title> 선택자 </title>
<script src="js/jquery.js"></script>
<script>
$(function () {
$("#list_1").css("border", "2px dashed #f00");
});
</script>
</head>
<body>
<h1>인접 관계 선택자</h1>
<ul id="wrap">
<li>리스트1
<ul>
<li id="list_1">리스트1-1</li>
<li>리스트1-2</li>
</ul>
</li>
<li>리스트2</li>
<li>리스트3</li>
</ul>
</body>
</html>

<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title> 선택자 </title>
<script src="js/jquery.js"></script>
<script>
$(function () {
$("#wrap h1").css("background-color", "yellow").css("border", "2px dashed #f00");
});
</script>
</head>
<body>
<div id="wrap">
<h1>인접 관계 선택자</h1>
<p>내용1</p>
<section>
<h1>하위 요소 선택자</h1>
<p>내용2</p>
</section>
</div>
</body>
</html>

<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title> 선택자 </title>
<script src="js/jquery.js"></script>
<script>
$(function () {
$("#wrap > h1").css("border", "2px dashed #f00");
$("#wrap > section").children()
.css({
"background-color": "yellow",
"border": "2px solid #f00"
});
});
</script>
</head>
<body>
<div id="wrap">
<h1>인접 관계 선택자</h1>
<p>내용1</p>
<section>
<h1>자식 요소 선택자</h1>
<p>내용2</p>
</section>
</div>
</body>
</html>

<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title> 선택자 </title>
<script src="js/jquery.js"></script>
<script>
$(function () {
var style_1 = {
"background-color": "#0ff",
"border": "2px solid #f00"
}
var style_2 = {
"background-color": "#ff0",
"border": "2px dashed #f00"
}
//txt 이전 형제 요소
$(".txt").prev().css(style_1);
//txt 다음 형제 요소
$(".txt").next().css(style_2);
//다른 방법
$(".txt + p").css(style_2);
//txt다음 다음 요소
$(".txt").next().next().css(style_2);
});
</script>
</head>
<body>
<div id="wrap">
<h1>인접 관계 선택자</h1>
<p>내용1</p>
<p class="txt">내용2</p>
<p>내용3</p>
<p>내용4</p>
</div>
</body>
</html>

<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title> 선택자 </title>
<script src="js/jquery.js"></script>
<script>
$(function () {
var style_1 = {
"background-color": "#0ff",
"border": "2px solid #f00"
}
var style_2 = {
"background-color": "#ff0",
"border": "2px dashed #f00"
}
//txt 이전 형제 요소 전체 선택
$(".txt").prevAll().css(style_1);
//txt 다음 형제 요소 전체 선택
$(".txt").nextAll().css(style_2);
});
</script>
</head>
<body>
<div id="wrap">
<h1>인접 관계 선택자</h1>
<p>내용1</p>
<p class="txt">내용2</p>
<p>내용3</p>
<p>내용4</p>
</div>
</body>
</html>

<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title> 선택자 </title>
<script src="js/jquery.js"></script>
<script>
$(function () {
var style_1 = {
"background-color": "#0ff",
"border": "2px solid #f00"
}
//txt의 모든 형제 선택
$(".txt").siblings().css(style_1);
});
</script>
</head>
<body>
<div id="wrap">
<h1>인접 관계 선택자</h1>
<p>내용1</p>
<p class="txt">내용2</p>
<p>내용3</p>
<p>내용4</p>
</div>
</body>
</html>

<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title> 선택자 </title>
<script src="js/jquery.js"></script>
<script>
$(function () {
var style_1 = {
"background-color": "#0ff",
"border": "2px solid #f00"
}
//txt3 이전 형제들 부터 title전 까지
$(".txt3").prevUntil(".title").css(style_1);
//txt3 다음 형제들부터 txt6전 까지
$(".txt3").nextUntil(".txt6").css(style_1);
});
</script>
</head>
<body>
<div id="wrap">
<h1 class="title">선택자</h1>
<p>내용1</p>
<p>내용2</p>
<p class="txt3">내용3</p>
<p>내용4</p>
<p>내용5</p>
<p class="txt6">내용6</p>
</div>
</body>
</html>

<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title> 선택자 </title>
<script src="js/jquery.js"></script>
<script>
$(function () {
$(".txt1").parents().css("border", "2px dashed #00f");
$(".txt2").parents("div").css("border", "2px solid #f00");//상위 요소중 선택한 요소만 선택
});
</script>
</head>
<body>
<h1 class="title">선택자</h1>
<section>
<div>
<p class="txt1">내용</p>
</div>
</section>
<section>
<div>
<p class="txt2">내용</p>
</div>
</section>
</body>
</html>

<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title> 선택자 </title>
<script src="js/jquery.js"></script>
<script>
$(function () {
$(".txt1").closest("div").css("border", "2px solid #f00");
});
</script>
</head>
<body>
<h1 class="title">선택자</h1>
<div>
<div>
<p class="txt1">내용</p>
</div>
</div>
</body>
</html>
