JAVASCRIPT
JAVASCRIPT ) 함수
Hweb
2024. 7. 3. 15:43
함수는 선언문이다.
따라서 함수를 호출해줘야 한다.
함수를 실행하지않으면 함수 자체를 값으로 처리한다.
//함수 선언
function 함수명( [인자...[,인자]] ){
코드
return 반환값
}
//함수 호출
함수명();
파라미터(parameter)와 아규먼트(argument) 매개변수
function 함수명( 파라미터a, 파라미터b ){
코드
return 반환값
}
함수명(아규먼트a, 아규먼트b);
함수 자체가 아규먼트가 되어 파라메터로 받을수있다.
function anyFu() {
document.write("zard");
}
function runFu(inFu) {
inFu();
}
runFu(anyFu);
아규먼트가 없을경우 파라메타의 디폴트값을 설정할 수 있다.
아규먼트는 순서대로 파라메타로 넘겨진다. 따라서 파라메타 b에만 넘길수는 없다.
function myF( a=10, b=20 ){
return a + b;
}
document.write( myF() );
//30
function myF( a=10, b=20 ){
return a + b;
}
document.write( myF( 20 ) );
//40
함수의 length
함수의 length는 파라메타의 길이를 말하며 인자의 length 또한 구할 수 있다.
function myF(a, b, c){
document.write(myF.length); //3
document.write(arguments.length); //5
}
myF(1,2,3,4,5);
지역변수와 전역변수
let a = 10; //전역변수
document.write( a + "<br>" );
function example() {
let a = 30; // 지역변수
document.write( a + "<br>" );
}
example();
document.write( a + "<br>" );
// 10
// 30
// 10
Procedure와 Funtion
함수는 Procedure와 Funtion으로 나눌수있는데
return이 있는 함수는 Funtion. return이 없는 함수는 Procedure로 나눈다.
하지만 자바스크립트에서는 함수를 나누지않고 Funtion으로 통일한다.
// Procedure
function aaa() {
document.write("hello");
}
//Function
function bbb() {
return "hello";
}
aaa();
document.write( bbb() );
자기호출함수
자기호출함수는 호출되면 증발하기때문에 메모리를 잡아먹지않아서 실제로 많이쓴다고함.
(function anyFu( inString ) {
document.write( inString );
})("zard");
Anonymous 무명함수
무명함수는 이름이 없는 함수이다.
(function ( inString ) {
document.write( inString );
})("하이");
const myA = [
function(){document.write("0");},
function(){document.write("1"); return "하이";},
function(){document.write("2");}
]
document.write( myA[0] ); //function(){document.write("0");}
document.write( myA[1]() ); //1하이
document.write( myA[2]() ); //2undefined
const myO = {
zard: function(aaa){document.write( aaa );},
love: function(){document.write( "love" );}
}
myO.zard("cdr"); //cdr
document.write(myO.love); //function(){document.write( "love" );}
함수와 값의 처리
function cal(func, num){
return func(num)
}
function a(num){
return num+1
}
function b(num){
return num-1
}
alert(cal(a, 1));
alert(cal(b, 1));
함수는 함수 자체로 값이기때문에 파라메타에 함수를 넘길수 있다.
화살표 함수
함수는 return값이 있는 함수와 return값이 없는 Procedure(프로시저), 객체 세가지 의미로 쓰인다.
의미가 구분되기때문에 의미에따라 다르게 쓰기를 원했고
return값이 있는 함수와 return값이 없는 Procedure(프로시저)는 화살표 함수로
객체로 쓰인 함수는 class 문법으로 사용하기로 한다.
하위호환(이전에 적은 코드들을 다 바꿀 수는 없으니까)의 문제로 Function이 그대로 남아있긴하지만
반응형