컴퓨터 프로그래밍/수업
2020.05.22_1
깝돌이
2020. 5. 22. 10:15
1. 자바스크립트의 기본적인 내용
- data type
- 변수가 가지는 특징
- 함수가 가지는 특징
- 객체
2. 자바스크립트를 이용한 이벤트----> jQuery---->bootstrap
3. DOM
- 다큐먼테이션안에서는 모든 태그가 객체로 만들어져서 올라갑니다.
- data분석 하고 할때, 내가 뽑아낸 데이터를 웹으로 출려할때 DOM기술이 쓰입니다.
- html형태를 핸들링할 때, 태그로 파싱된 데이터를 핸들링 할때 쓸 수 있는 방식 => DOM방식과 삭시 방식이 있습니다. - 삭스방식은 확 읽어서 뿌릴때, DOM방식은 가져와서 그거를 조작해서 쓸 때 쓰입니다.
4. BOM
변수
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
var myName = "james";
firstName = "Gosling"; //자동으로 전역변수에 추가된다.
name = "james Gosling";
console.log(myName);
console.log(firstName);
console.log(name);
//es6//2015....변수의 난해함 때문에 let, const가 나와서 좀 명확히 해줄 수 있는데, 여전히 아래와 같이 쓴다...
function showAge(){
age = 90;//선언 안하면, age는 전역 변수로 됩니다.
console.log(age);
}
showAge();
console.log(age);
</script>
</head>
<body>
</body>
</html>
함수
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>함수 선언하는 2가지 방법:: 익명함수|선언적 함수 선언</title>
<script type="text/javascript">
//func(); 이 위치에서는 에러가 떠서 호출이 안됩니다.
//1. 익명함수 재정의
var func = function(){
alert("func A..")
}
var func = function(){
alert("func B..")
}
func(); 이거는 호출 되서 실행이 됩니다. 변수 명으로 함수 처럼 사용합니다.
//2. 선언적 함수: 먼저 메모리에 올려놓고 실행합니다. 그래서 호출 순서가 상관 없습니다
func();
function func(){alert("func A..")}
function func(){alert("func B..")}
//3. 익명함수+선언적 함수... 실행순서
//func(); 선언적 함수가 호출 됩니다.
var func = function(){alert("func A..");}//2번: 나중 생성
function func(){alert("func B..");}//1번: 먼저 생성
func();//선언적 함수가 우선 실행되고 그다음에 익명함수가 실행되서 func A..가 됩니다.func B를 덮어씀.
</script>
</head>
<body>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
function calc(x,y){ //calc 변수 생성하고 함수 할당
return x+y;
}
console.log(calc(5,3)); // 8이 아니라 15가 출력됨,
//왜냐면 선언적 함수는 먼저 로딩에 되고 하기 때문에
function calc(x,y){ //기본 calc 변수에 곱셈 기능을 가진 새로운 함수 할당
return x*y;
}
console.log(calc(5,3));// 15출력
</script>
</head>
<body>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
var calc = function(x,y){ //calc 변수 생성하고 함수 할당
return x+y;
}
console.log(calc(5,3)); // 8
var calc = function(x,y){ //기본 calc 변수에 곱셈 기능을 가진 새로운 함수 할당
return x*y;
}
console.log(calc(5,3));// 15출력
</script>
</head>
<body>
</body>
</html>
객체 생성 방법
<!--
자바를 다뤄봤따면 객체를 생성할때 클래스 없이는 불가능하다.(배열제외)
즉, 클래스를 기반으로 해서 객체가 생성되어진다.
하지만, 자바스크립트에서는 클래스가 존재하지 않는다.
자바스크립트 Object : 속성과 메소드를 가진 구현체
객체의 유형
1. 리터럴객체, JSON 객체
2. 생성자 함수를 이용한 객체 생성
3. 함수를 이용한 객체 생성
-->
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>javascript 객체 만드는 유형 정리</title>
<script type="text/javascript">
//1. 객체 리터럴: 속성: 속성값(key:value)->json(중요합니다. )
var p1 ={name:"홍길동", phone:"010-5621-4472", age:20}; //객체입니다.
console.log(p1);
//2. 생성자 함수를 이용해서 객체 생성
var p2 = new Object();// 일반함수와 구분 하기 위해서 대문자로 시작
p2.name = "홍길동";//이부분이 실행되면서 빈 객체에 값이 할당되어진다.
p2.phone ="010-5621-4472";
p2.age = 20;
console.log(p2);
//3. 함수를 이용한 객체 생성
p2.getInfo = function(){
return this.name+" 님의 나이는 "+this.age;
}
console.log(p2.getInfo());
//4. 배열 객체...다른 객체와 비교해서 특이한점은 키값이 없습니다. 다른 타입의 값 저장 가능
var p3 = [1, 22, 'Hello'];
console.log(p3);
</script>
</head>
<body>
</body>
</html>
객체 활용
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>literal, json</title>
<script type="text/javascript">
var product = {
name:'Encore',
price:'1500000원',
language:'한국어',
desc:'상세내역'
};
//복합연산자
var output='';
for(var key in product){//for in
output +='●'+key+" : "+product[key]+'\n';
}
alert(output);
</script>
</head>
<body>
</body>
</html>
html을 메모리에 올리면 dom구조로 됩니다. 아래와 같은 document 구조가 됩니다. 모든 태그가 객체화 되서 올라갑니다.
html - head - body - h2
- P
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h2>JavaScript Object::json...</h2>
<p id="view"></p>
<script>
var person = {
name:"john",
age:50,
eyecolor:'blue'
};
document.getElementById("view").innerHTML =
person.name+" is "+person.age+" year old....."
</script>
</body>
</html>
----
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h2>JavaScript Object::json...</h2>
<p id="view"></p>
<script>
var person = {
firstName:"john",
lastName:"Smith",
age:50,
eyecolor:'blue',
fullName:function(){
return this.firstName+" "+this.lastName;
}
};
document.getElementById("view").innerHTML =
person.fullName();
</script>
</body>
</html>
생성자형 객체 활용
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>생성자 함수 이용한 객체 생성</title>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
function Product(pname, price, cnt){// 생성자형 객체는 함수와 구분하기 위해서 대문자로 시작한다.
//this.속성
this.pname = pname;
this.price = price;
this.cnt =cnt;
//this.메소드
this.buy = function(){
//정의...메서드가 하는일.....
document.write('<h2>구매 물품 정보 보기</h2>')
document.write('<h3>물건명: '+this.pname+'</h3>')
document.write('<h3>가 격: '+this.price+'</h3>')
document.write('<h3>갯 수: '+this.cnt+'</h3>')
document.write('<h3>총 계: '+(this.price*this.cnt)+'</h3>')
}
}
$(document).ready(function(){
$('h2').text('시작');
//생성자 객체
var p1 = new Product('NoteBook1', 1000000, 3);
var p2 = new Product('NoteBook2', 1500000, 6);
var p3 = new Product('NoteBook3', 2400000, 1);
//함수 호출
p1.buy();
document.write('<h3>========================================</h3>');
p2.buy();
document.write('<h3>========================================</h3>');
p3.buy();
document.write('<h3>========================================</h3>');
});
</script>
</head>
<body>
<h2></h2>
</body>
</html>
self_constructor
<!--
해보기
Student 생성자 객체 선언,
속성: 이름, 자바(Score), 파이썬(Score), html5(Score)
함수1(총합)
함수2(평균)
함수3(정보들을 출력)
이름 자바 파이썬 html 총점 평균
제임스 70 80 90 240 80
이때 학생은 총 3명으로 객체 생성
html body 부분 안에다가 알아서...특정 영역을 지정해서 해주세요.
-->
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>생성자 함수 이용한 객체 생성::self</title>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
function LanguageScore(name, java, python, html5){
this.name = name;
this.java = java;
this.python = python;
this.html5;
this.totalScore = function(){
return java+python+html5;
}
this.average = function(){
return this.totalScore()/3;
}
//e6 :: 1)`(grave accent) 2) arrow function(나중에....vue.js) 3) var---->let, const
this.showInfo = function(){
document.write('<table border = 1><tr><th>이름</th><th>자바</th><th>파이썬</th><th>html</th><th>총점</th><th>평균</th></tr>');
doucument.write('<tr><td>'+this.name+'</td><td>'+this.java+'</td><td>'+this.python+'</td><td>'+this.html5+'</td><td>'+this.totalScore()+'</td><td>'+this.average()+'</td></tr></table>');
//documnet.write(`<tr><td>${this.name}</td><td>${this.java}</td><td>${this.python}</td><td>${this.html5}</td><td>${this.totalScore()}</td><td>${this.average()}</td></tr></table>`);
}
}
$(document).ready(function(){
var p1 =new LanguageScore('이', 100, 100, 100);
var p2 =new LanguageScore('오', 70, 70, 70);
var p3 =new LanguageScore('한', 80, 80, 80);
document.write('<h3>========================================</h3>');
p1.showInfo();
document.write('<h3>========================================</h3>');
p2.showInfo();
document.write('<h3>========================================</h3>');
p3.showInfo();
document.write('<h3>========================================</h3>');
});
</script>
</head>
<body>
</body>
</html>
조건문 등등
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>브라우저로 출력하는 여러가지 형식과 조건문, 기타 등등</title>
<script type="text/javascript">
//1. write()함수는 인자값으로 받은 내용을 브라우저 화면으로 출력하는 기능....
/* document.write(50+70+'<br>');//연산이 적용되고 출력이 됨.120
document.write(eval('50+70')+'<br>'); //문자열을 계산하려면....eval()함수를 이용합니다. 120
document.write(eval('50.6+70')+'<br>'); //문자열을 계산하려면....eval()함수를 이용합니다. 120.6
document.write(eval('56.7+23')+'<br>'); //문자열을 계산하려면....eval()함수를 이용합니다. 79.7
document.write(eval('56.7'+'23')+'<br>'); // 문자와 문자를 더함 56.723
document.write(parseFloat('56.7')+parseInt('23')+'<br>'); //형변환
document.write(parseFloat('56.7')+parseInt('23.6')+'<br>'); //형변환 parseInt하면 실수의 경우 절삭 79.7
*/
//2. 팝업창(대화창) 종류와 띄우는 방법:: alert(), confirm(), prompt()
/*
* alert - 이걸 로 실행여부 확인
* confirm - 중요한 처리를 앞두고(삭제, 수정) 한번더 확인할 필요가 있을때 띄우는 창
* prompt - 데이타를 입력 받아서 처리할 때 사용
*/
/*
1)
var ans = confirm("정말로 탈퇴 하시겠습니까?");
// yes button과 cancle button이 있는데, yes는 true, cancle은 false가 리턴됩니다.
//ans에 결과가 저장되니까, 조건문에 넣습니다.
if(ans) document.write("삭제 되셨습니다...<br");//true ==1 if(ans ==1)로 쓸수 있음.
else document.write("삭제 취소되셨습니다...<br");
*/
/*
2)
if(confirm("정말로 탈퇴 하시겠습니까?"))
document.write("삭제 되셨습니다...<br");
else document.write("삭제 취소되셨습니다...<br"); */
var name = prompt("당신의 차 번호를 입력하세요.....");
document.write(name);
</script>
</head>
<body>
</body>
</html>