js 함수
function 함수명([매개변수. 매개변수...]){
함수 호출 시 실행할 코드
[return 결괏값;]
}
function test1(){
console.log("test1 함수 실행");
}
자바스크립트는 함수를 변수에 할당할 수 있음.
입급객체, 1종객체/변수 -> 변수에 담을 수 있다, 함수의 인자로 전달이 가능, 함수 결과로 반환할 수 있다.
js에서 함수는 1종객체이기 때문에 위에 모든 게 가능하다.
js에서 함수의 이름이 필수는 아니다. 다만 호출을 위해서는 함수의 이름이 필요하기 때문에 필요시 작성한다.
function test1(){
console.log("test1 함수 실행");
}
const test3 = function(){
console.log("test2 함수 실행");
}
test1();
test3();
test1();
js는 오버로딩을 지원하지 않으며 매개변수의 갯수가 달라도 동일 메서드로 인식된다.
let test4 = function(name){
console.log(arguments)
console.log("test4 함수 실행")
console.log(name);
}
test4();
test4("최지원");
test4("최지원", 55);
test4("최지원", 55, "경기도 광명시", ' 철산2동');
let test5 = () => 200;
window.console.log(test5());
js의 함수는 기본적으로 arguments객체를 가지고있음 -> 전달받은 모든 인자값이 들어있는 배열
익명 함수
변수 | 속성 = function([매개변수. 매개변수...]){
함수 호출시 실행할 코드
[return 결괏값;]
}
<button id="btn">이벤트 속성으로 실행</button>
<button onclick="test2()">변수로 실행</button>
<div id="area2" class="area"></div>
<script>
let test2 = function(){
document.getElementById('#area2').innerHTML = '익명함수 실행됨<br>';
}
let btn = document.getElementById('btn');
btn2.onclick = function(){
document.getElementById('#area2').innerHTML = '이벤트 핸들러로 실행됨<br>';
}
//이벤트 : 브라우저에서 발생하는 모든 동작(click, keyup, drag, load...)
//이벤트 핸들러 : 특정 이벤트가 발생했을 때 실행되는 함수
</script>
함수의 매개변수
매개 변수 갯수, 타입이 달라도 정상적으로 실행됨.
매개변수 갯수가 부족하면 undefined를, 많으면 받지 않음
<button onclick="test3('홍길동', 20, '남');">실행확인</button>
<button onclick="test3('홍길동', 20);">실행확인</button>
<button onclick="test3('홍길동', 20, '남', '서울특별시', false);">실행확인</button>
<div id="area3" class="area"></div>
<script>
function test3(agr1, agr2, agr3){
console.log(arguments); //함수 호출시 전달된 인자를 내부적으로 arguments에 배열로 담아둠
document.getElementById('area3').innerHTML = agr1 + " " + agr2 + " " + agr3;
}
</script>
함수, 객체를 매개변수로 활용
간단한 서버 - 클라이언트 기본 동작 예시
<script>
//아이디, 비번을 전달해서 유저 정보 가져오기
function login(userInfom, callback){
//로그인 정보를 가지고 서버에 전달
//결과에 따라서 로그인 성공
console.log("서버에 요청 : " + loginInfo);
setTimeout(function(){ //서버에 요청을 보내고 응답에 3초정도 시간이 걸린다는 가정
//서버에서 응답 성공 후 user정보 반환
let serverReturnInfo = {
userId : 'user01',
userPwd : 'pass01',
userName : '홍길동',
age : 20
}
callback(serverReturnInfo);
}, 3000); //첫번째 인자로 전달된 함수는 두번째 인자의 시간(ms)만큼 딜레이 후 실행됨
console.log("실행 후")
}
let id = 'user01';
let pwd = 'pass01';
login({
userId : id,
userPwd : pwd
}, function(userInfo){
console.log(userInfo + "로그인 성공");
});
</script>
스코프와 this
스코프 : 이름을 어디서 찾을 것인가?(사용 시점이 중요)
this : 사용시점의 스코프를 가리킴(나를 누가 호출했는가?)
인라인에서의 this를 사용시 사용한 태그요소를 객체로 전달
<button onclick="test4(this)">1</button> <!-- 인라인 이벤트에서 this를 사용시 항상 현재 요소 자신을 가르킨다. -->
<button onclick="test4(this.innerHTML)">2</button>
<input type="button" value="3" onclick="test4(this.value)">
<button id="btn4">4</button>
<script>
console.log(this); //window
function test4(_this){
console.log("_this", _this); //button
console.log("this", this); //window
}
test4();
const btn4 = document.getElementById('btn4');
btn4.onclick = function(){
console.log(this); //button
}
</script>
<button onclick="test5(this)">클릭</button>
<script>
function test5(_btn){
if(_btn.style.background !== "red"){
_btn.style.background = "red";
}else{
_btn.style.background = "white";
}
}
</script>
일반적인 값 반환과 함수 반환
<h3>일반적인 값 반환</h3>
<button onclick="test6()">실행</button>
<div id="area4" class="area"></div>
<script>
function run(){
const value = parseInt(Math.random() * 100 + 1);
console.log(value);
return value;
}
function test6(){
document.getElementById('area4').innerHTML += ('랜덤값' + run() + '<br>');
}
</script>
<h3>함수를 반환</h3>
이름 : <input type="text" id="name">
<button onclick="test7()()">실행</button>
<script>
function test7(){
const inputE1 = document.getElementById('name');
return function(){
alert(inputE1.value);
}
// return function(){
// alert(inputE1.value);
// }() -> test7()() 동일한 결과
}
</script>
자바와 다르게 함수 자체를 반환 가능하며 return 함수 뒤에 ()를 붙이거나 함수를 부르는 곳에 ()를 추가로 붙여야 함.
html 요소에 접근하기(해당 요소 객체 가져오기)
1. 아이디를 이용해서 요소 가져오기
<div class="area" id="area1">area1 영역</div>
<button onclick="acessId()">아이디 접근</button>
<script>
// document.getElementById("요소의 아이디")
function acessId(){
let area1 = document.getElementById("area1");
area1.className = 't1 t2 t3';
area1.style.background = 'yellow';
area1.style.width = '200px';
area1.style.height = '200px';
area1.style.borderRadius = '100px';
area1.innerText = '클릭된 area1영역';
}
</script>
2. 태그명으로 요소 가져오기
<ul>
<li>안녕하세요</li>
<li><h2>안녕하세요</h2></li>
<li>안녕하세요</li>
<li>안녕하세요</li>
<li>안녕하세요</li>
</ul>
<button onclick="accessTagName()">태그명으로 검색</button>
<script>
// 태그명으로 요소를 가져올 때
// document.getElementsByTagName('요소의 태그명');
function accessTagName(){
let elList = document.getElementsByTagName('li');
console.log(elList.length);
console.log('첫번째 요소의 html : ' + elList[1].innerHTML);
console.log('두번째 요소의 html : ' + elList[1].innerText);
for(let i=0; i<elList.length; i++){
elList[i].innerHTML = (i+1) + '번째 요소';
elList[i].style.color = 'blue';
}
}
</script>
그 외
document.getElementsByName('요소의 네임 속성 값'); -> 여러개 반환
document.getElementsByClassName('요소의 클래스명'); -> 여러개 반환
내가 원하는 요소 자유롭게 가져오기
<div id="tmp1">테스트</div>
<div id="tmp2">
<h2>안녕하세요</h2>
<h2>홍길동입니다</h2>
</div>
<span>span 요소 입니다</span>
<h2>h2 요소 입니다</h2>
<br>
<button onclick="accessSelector()">선택자로 검색</button>
<script>
//선택자를 이용해서 요소를 가져올 때 사용
// document.querySelector('선택자') -> 요소 한 개만 반환, 찾는 요소가 없을 때는 null 반환, 조건에 맞는 값이 여러개여도 한개만 가져옴
// document.querySelectorAll('선택자') -> 선택한 요소 전부 배열로 반환, 찾는 요소가 없을 때는 빈 배열 반환
function accessSelector(){
const div1 = document.querySelector('#tmp1');
const h2E1 = document.querySelectorAll('#tmp2 h2');
const spanE1 = document.querySelector('#tmp2+span');
console.log(div1);
console.log(h2E1);
console.log(spanE1);
}
</script>
객체
객체는 {} 형태를 이용해서 생성하고 중괄호 안에 이 객체에 필요한 속성과 값을 정의
속성명 : 속성값 (key : value) 형태로 정의
속성값으로는 모든 자료형의 값을 담을 수 있음
변수 = {
속성명 : 속성값,
속성명 : 속성값,
속성명 : 속성값,
...
}
<button onclick="test1()">실행</button>
<div id="area1" class="area"></div>
<script>
function test1(){
const arr = ["Dry Mango", 4000, "pickle", ["mango", "sugar"]];
//0번재는 제품명, 1번째는 가격, 2번째는 종류, 3번째는 재료들 ->
// 순서 기반으로 작성시 명확하게 값을 지정할 수 없으며, 쉽게 순서에따라 잘못 사용할 확률이 높음
//js의 배열 -> java의 컬렉션(ArrayList)과 유사
const product = {
pName : "Dry Mango",
price : 4000,
kind : "pickle",
ingredient : ["mango", "sugar"],
toString(){
return this.pName + " " + this.price + " " + this.kind + " " + this.ingredient;
}
}
//js의 객체 -> 자바의 컬렉션(HashMap)과 유사
console.log(typeof product);
const area1 = document.getElementById('area1');
area1.innerHTML += ("product : " + product + "<br>");
//js에서는 문자열 + 객체 -> 암묵적인 자동 형변환 발생,
// 기본적으로 js도 기본적으로 toString()이라는 메서드를 호출
//객체의 기본 toString() -> [object Object]를 반환
//객체의 속성에 접근하는 방법
//방법1. .를 이용 : 객체.속성명
aera1.innerHTML += ("product.pName : " + product.pName + "<br>");
aera1.innerHTML += ("product.price : " + product.price + "<br>");
aera1.innerHTML += ("product.kind : " + product.kind + "<br>");
//방법2. []를 이용 : 객체['속성명']
aera1.innerHTML += ("product.pName : " + product['pName'] + "<br>");
aera1.innerHTML += ("product.price : " + product['price'] + "<br>");
aera1.innerHTML += ("product.kind : " + product['kind'] + "<br>");
}
</script>
객체 메서드 속성
객체의 속성 중 함수 자료형인 속성을 메서드라고 부름
<button onclick="test2()">실행</button>
<div id="area2" class="area small"></div>
<script>
function test2(){
const area2 = document.querySelector('#area2');
const name = "홍길동";
const eat = function(food){
console.log(name + "은 " + food + "먹는다");
}
eat("바나나킥");
const gildong = {
name : "홍길동",
gender : "남",
eat : function(food, screen){
console.log(this.name + "은 " + food + "먹는다");
screen.innerHTML += this.name + "은 " + food + "먹는다<br>";
}
}
gildong.eat("피자", area2);
}
</script>
객체 배열을 사용한 다량의 데이터 관리
자바처럼 for문으로 배열 관리.
innerHTML을 이용해 배열을 화면에 생성
<button onclick="test3();">실행</button>
<div id="area3" class="area big"></div>
<script>
function test3(){
// 학생 리스트 -> 서버로부터 데이터를 받으면 아래와 같이 객체의 배열 형태의 데이터를 받음
const stdList =[
{name: "홍길동", java: 75, db: 90, front: 100},
{name: "홍길서", java: 71, db: 91, front: 90},
{name: "홍길남", java: 72, db: 92, front: 80},
{name: "홍길북", java: 73, db: 93, front: 70},
{name: "홍길중", java: 74, db: 94, front: 60}
]
//모든 학생의 이름, 총점, 평균정보를 area3요소에 나타내자.
for(let i=0; i<stdList.length; i++){
stdList[i].totalScore = function(){
return this.java + this.db + this.front;
};
stdList[i].avgScore = function(){
return this.totalScore() / 3;
};
}
const area3 = document.getElementById('area3');
area3.innerHTML = "";
for(let i=0; i<stdList.length; i++){
area3.innerHTML += `<div style="margin-bottom: 7px;">
<h5>이름 : ${stdList[i].name}</h5>
<h5>총점 : ${stdList[i].totalScore()}</h5>
<h5>평균 : ${stdList[i].avgScore()}</h5>
</div>`;
}
}
</script>