Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
Tags
- jQuery
- SQLD후기
- JSP
- 기초
- Slide
- sqld
- 코딩공부
- TweenMax.js
- 로또 회차
- VANILLA
- 텍스트조절
- JS
- sqld52회차
- 마우스커서
- Python
- github
- 애니메이션
- git
- 프론트앤드키워드
- 웹접근성
- 웹개발키워드
- 웹표준
- 바닐라자바스크립트
- IP차단
- 팝업레이어
- 바닐라 자바스크립트
- asp
- CSS
- 바닐라스크립트
- SQL
Archives
- Today
- Total
단비의 코딩 공부 blog
[Vanilla JS]study 12일차 - ES6 2 본문
1. 변수키워드
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>ES6 문법</title>
</head>
<body>
<script>
//1. var : 초기 변수 키워드 - 함수를 기준으로 전역변수와 지역변수로 나뉨
var test1 = 10;
var test1 = 20; //재선언이 가능
test1 = 30; //재할당 가능
//2. let - 코드블록 { }을 기준으로 전역변수와 지역변수로 나뉨
let test2 = 10;
//let test2 = 20; //재선언이 불가능
test2 = 30; //재할당 가능
//3. const - 코드블록 { }을 기준으로 전역변수와 지역변수로 나뉨
const test3 = 10;
test3 = 30; //재선언, 재할당 불가능
</script>
</body>
</html>
2. 화살표 함수
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>ES6 문법</title>
</head>
<body>
<script>
//1. 선언적 함수
function test1(){
}
//2. 변수식 함수
let test2 = function(){
}
//3. 화살표 함수
test3 = () => {
}
</script>
</body>
</html>
3. 향상된 객체리터럴
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>ES6 문법</title>
</head>
<body>
<script>
//1. 변수명과 속성명이 같으면 값을 작성하지 않아도 됨
let a = '테스트', b = 10, c = [10,20,30];
let test = {
a,
b,
c
}
console.log(test.a);
console.log(test.b);
console.log(test.c);
//2. 객체에 메서드 작성시 function이 생략 가능
var test2 = {
//원래 문법
a: function(){
alert('함수키워드 작성');
},
//향상된 문법
b(){
alert('함수키워드 미작성');
}
}
test2.a();
test2.b();
</script>
</body>
</html>
4. 생성자 함수
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>ES6 문법</title>
</head>
<body>
<script>
//생성자 함수 : 객체의 설계도 - 코드 절감(메모리절감)
//평균을 구하는 생성자 함수
function Score(name, kor, eng, math){
this.name = name;
this.kor = kor;
this.eng = eng;
this.math = math;
}
//메서드 공통이라서 프로토타입으로 작성
Score.prototype.avg = function avg(){
return this.name + '의 평균 : ' + ((this.kor + this.eng + this.math) / 3).toFixed(2);
}
//인스턴스 생성
var s01 = new Score('홍길동',90,80,75);
var s02 = new Score('김철수',100,80,75);
var s03 = new Score('박영희',80,80,75);
alert(s01.avg());
alert(s02.avg());
alert(s03.avg());
</script>
</body>
</html>
5. class의 선언
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>ES6 문법</title>
</head>
<body>
<script>
//class : 객체를 만들기 위한 설계도
// : 객체를 생성하기 위한 속성과 메서드로 정의되어있는 객체
// : 설계도를 바탕으로 여러 개의 인스턴스를 생성
//생성자함수와 다른 점
//1. function키워드 대신 class키워드를 사용
//2. 속성들을 constructor() 메서드 내부에 할당
//클래스명은 첫글자를 대문자로 쓰는 것이 관례
class Car{
constructor(name){
this.brand = name;
}
}
//인스턴스 생성
let car01 = new Car('bmw');
let car02 = new Car('ford');
//출력
alert(car01.brand);
alert(car02.brand);
/*
- class문법
1. 선언 문법
class 클래스{
constructor(){
this.속성명 = 값;
}
메서드명(){
}
}
2. 인스턴스생성문법
let인스턴스명 = new 클래스명();
*/
</script>
</body>
</html>
6. class의속성과메서드
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>ES6 문법</title>
</head>
<body>
<script>
//클래스 선언
class Car{
//속성선언 - constructor()메서드 내부에 작성
constructor(name){
this.brand = name;
}
//메서드 선언
present(){
return '나는 ' + this.brand + '의 자동차를 소유하게 되었다.';
}
}
//인스턴스 생성
let mycar01 = new Car('벤츠');
let mycar02 = new Car('볼보');
let mycar03 = new Car('포드');
//출력
alert(mycar01.present());
alert(mycar02.present());
alert(mycar03.present());
</script>
</body>
</html>
7. 부모클래스와 자손클래스
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>ES6 문법</title>
</head>
<body>
<script>
//상속 : 부모클래스의 속성과 메서드를 자손 클래스에 물려주는 것
//부모클래스 : 상위클래스, 슈퍼클래스
//자손클래스 : 하위클래스, 파생클래스
//나눠서 사용하는 이유
//1. 이미 잘 개발된 클래스를 재사용해서 새로운 클래스를 만들기 위해
//2. 부모클래스 수정으로 모든 자손클래스가 수정되는 효과를 줘서 유지 보수 시간을 최소화
//브랜드 확인 : 부모클래스
class Car{
constructor(brand){
this.brand = brand;
}
output(){
return this.brand + '의 자동차를 소유하게 되었다.';
}
}
//모델명 확인 : 자손 클래스
//class 자손클래스명 extends 부모클래스 { }
class Model extends Car {
constructor(brand,name){
super(brand); //super() 메서드는 부모 클래스를 나타냄
this.name = name;
}
show(){
return this.output() + '자동차명은' + this.name + '이다.';
}
}
//인스턴스 생성
let mycar01 = new Model('Ford','Mustang');
let mycar02 = new Model('현대','캐스퍼');
//출력
alert(mycar01.show());
alert(mycar02.show());
</script>
</body>
</html>
8. 클래스 정리
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>ES6 문법</title>
</head>
<body>
<script>
//클래스 : 객체의 설계도
//부모클래스 : 학생의 이름과 국영수점수를 받는 클래스제작
class Score{
constructor(name, kor, eng, math){
this.name = name;
this.kor = kor;
this.eng = eng;
this.math = math;
}
ScoreOutput(){
return this.name + '<br>' + '국어점수 : ' + this.kor + '<br>' + '영어점수 : ' + this.eng + '<br>' + '수학점수 : ' + this.math + '<br>';
}
}
//합계를 구하는 자손클래스
class Sum extends Score {
sumScore(){
return this.kor + this.eng + this.math;
}
sumOutput(){
return this.ScoreOutput() + '합계 : ' + this.sumScore() + '<br>';
}
}
//평균을 구하는 자손클래스
class Average extends Score {
avgScore(){
return ((this.kor + this.eng + this.math) / 3).toFixed(2);
}
avgOutput(){
return this.ScoreOutput() + '평균 : ' + this.avgScore() + '<br>';
}
}
//인스턴스 생성
let s01 = new Sum('홍길동', 90, 80, 98);
let s02 = new Average('홍길동', 90, 80, 98);
document.write(s01.sumOutput());
document.write(s02.avgOutput());
</script>
</body>
</html>
9. 비구조화 할당
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>ES6 문법</title>
</head>
<body>
<script>
//비구조화 할당 : 배열이나 객체에 속성값을 해체해서 각각의 변수에 담는 자바스크립트 표현식
//1. 배열 해체
const [cat, dog, tiger] = ['고양이', '강아지', '호랑이'];
//2. 객체 해체
const { cat2, dog2, tiger2 } = {
cat2 : '고양이',
dog2 : '강아지',
tiger2 : '호랑이'
}
</script>
</body>
</html>
10. 모듈화
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>ES6 문법</title>
</head>
<body>
<!-- html에서JS문서를 불러들여옴 -->
<script src="test101.js"></script>
<script src="test102.js"></script>
<script>
//모듈화 : 다른 파일의 JS기능을 특정 파일에 사용하는 것을 의미
//import : 다른 JS 문서를 불러들여옴
//export : 현재 JS 기능을 다른 파일에서 가져다 쓸 수 있도록 내보내는 키워드
//ES6이전에는 모듈화작업이 불가능
alert(test());
</script>
</body>
</html>
<script>
let a = 10;
function test(){
return a;
}
let a = 20;
//ES6이전에는 같은 JS문서끼리 변수나 함수를 공유하는 것이 불가능
//test();
</script>
11. import와export
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>ES6 문법</title>
</head>
<body>
<script src="test112.js"></script>
<!-- 브라우저가 아직 모듈화를 지원하지 않음 -->
<!-- 바벨같은 도구를 사용해서 ES5이하로 컴파일처리하면 사용 가능 -->
</body>
</html>
<script>
import num from './test111';
//import { 불러올 변수 또는 함수 } from '파일경로';
//import 변수명 as 별명 from '파일경로';
alert(num);
</script>
12. find메서드
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>ES6 문법</title>
</head>
<body>
<script>
//find() 메서드 : 함수의 조건을 통화한 첫번째 배열요소 값을 반환하는 메서드
//findIndex() 메서드 : 함수의 조건을 통과한 첫번째 배열 요소의 인덱스 번호를 반환
//ex) 20보다 큰 숫자 중 첫번째 값을 반환
let nums = [4, 9, 16, 25, 29];
//함수선언
test = x => {
return x > 20;
}
alert(nums.find(test));
alert(nums.findIndex(test));
</script>
</body>
</html>
13. map 메서드1
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>ES6 문법</title>
</head>
<body>
<script>
//map() : 배열의 함수를 호출해서 새로운 배열을 생성
//문법
//array.map(function(currentValue, index, arr){}, thisValue);
//currentValue : 필수값, 현재 배열의 요소 값 - 영문을 어떤 것을 쓰든 상관없음
//index : 현재 배열의 인덱스번호
//arr : 현재 요소의 배열
//thisvalue : this값으로 사용할 함수에 전달된 값
//1. 배열값을 제곱근으로 새로운 배열로 반환
const nums = [4,9,16,25,36];
const newNums = nums.map(Math.sqrt);
document.write('기존배열값 : ' + nums + '<br>');
document.write('제곱근배열값 : ' + newNums + '<br>');
</script>
</body>
</html>
14. map 메서드2
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>ES6 문법</title>
</head>
<body>
<script>
//map() : 배열의 함수를 호출해서 새로운 배열을 생성
//문법
//array.map(function(currentValue, index, arr){}, thisValue);
//currentValue : 필수값, 현재 배열의 요소 값 - 영문을 어떤 것을 쓰든 상관없음
//index : 현재 배열의 인덱스번호
//arr : 현재 요소의 배열
//thisvalue : this값으로 사용할 함수에 전달된 값
//1. 배열값을 제곱근으로 새로운 배열로 반환
const nums = [4,9,16,25,36];
square = x => {
return x * x;
}
const newNums = nums.map(square);
document.write('기존배열값 : ' + nums + '<br>');
document.write('제곱근배열값 : ' + newNums + '<br>');
</script>
</body>
</html>
15. map 메서드3
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>ES6 문법</title>
</head>
<body>
<h3>Avengers</h3>
<ul id="avengersList">
<!-- li태그를 동적 생성 -->
</ul>
<script>
//map() : 배열의 함수를 호출해서 새로운 배열을 생성
//문법
//array.map(function(currentValue, index, arr){}, thisValue);
//currentValue : 필수값, 현재 배열의 요소 값 - 영문을 어떤 것을 쓰든 상관없음
//index : 현재 배열의 인덱스번호
//arr : 현재 요소의 배열
//thisvalue : this값으로 사용할 함수에 전달된 값
//어벤져스 멤버들 이름을 firstname과 lastname을 따로 받아서 한번에 풀네임으로 처리
//변수의 이름 담은 배열
const avengers = [
{ firstname : '토니', lastneme : '스타크' },
{ firstname : '스티브', lastneme : '로저스' },
{ firstname : '브루스', lastneme : '배너' },
{ firstname : '토르', lastneme : '오딘스' },
{ firstname : '나타샤', lastneme : '로마노프' },
{ firstname : '클린톤', lastneme : '바톤' }
];
//문서객체 선택
const ulTag = document.getElementById('avengersList');
let liTag = ''; //반복문으로 값을 재할당 해야해서 let 선언
getFullName = item => {
return [item.firstname,item.lastneme].join(' ');
}
const avengersName = avengers.map(getFullName);
alert(avengersName);
for(let i in avengersName){
liTag += '<li>' + avengersName[i] + '</li>';
}
//innerHTML : 태그를 인식하는 문자열로 반환하는 속성
ulTag.innerHTML = liTag;
</script>
</body>
</html>
16. forEach 메서드
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>ES6 문법</title>
</head>
<body>
<h3>2022 KBO 정규리그순위</h3>
<div id="listBox">
</div>
<script>
//forEach() : 배열 값을 반복하는 메서드 - 매개변수 사용이 map메서드와 같음
const teams = ['ssg 랜더스', 'lg 트윈스','키움 히어로즈', 'kt 위즈', 'kia 타이거즈', 'nc다이노스', '삼성라이온즈', '롯데 자이언츠', '두산 베어스', '한화 이글스'];
//문서객체 담기
const listBox =document.getElementById('listBox');
let pTag = ''; //값을 재할당
teamsOutput = (team, index) => {
pTag += '<p>' + (index + 1) + '위 : ' + team + '</p>';
}
teams.forEach(teamsOutput);
listBox.innerHTML = pTag;
</script>
</body>
</html>
17. 지수연산자
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>ES6 문법</title>
</head>
<body>
<script>
// ** : 지수연산자
alert(5 ** 3); //5의 3승
</script>
</body>
</html>
'javascript&jquery' 카테고리의 다른 글
[Vanilla JS]study 14일차 - 웹 컨텐츠 제작 - 보드프리뷰 (0) | 2023.03.22 |
---|---|
[Vanilla JS]study 13일차 - 웹 컨텐츠 제작 - 드롭 다운 메뉴 (0) | 2023.03.21 |
[Vanilla JS]study 11일차 - ES6 (0) | 2023.03.13 |
[Vanilla JS]study 10일차 - DOM2 (0) | 2023.03.10 |
[Vanilla JS]study 9일차 - DOM (0) | 2023.03.06 |