[HTML] 함수정리 한번

비타민규·2023년 8월 5일

[HTML]

목록 보기
16/25

*함수정리*

<script>

	function func1(){ // 선언적 함수
		document.write('난 func1 함수야<br>');
	}
	func1();
    
	const myfunc = func1;
	//             func1() 실행결과를 줌. func1 함수 객체 자체를 줌(주소를 넘겼다 이해)
	myfunc();
    // const는 재할당, 재선언이 불가하다
	
	
function func2(arg1,arg2=20){
	let imsi = arg1 + arg2;
	return imsi;
}
let result = func2(1,2);
	document.write('<br>',result);
	
let result2 = func2("마라 귀신","효림");
	document.write('<br>',result2);

let result3 = func2(10);
	document.write('<br>',result3);
	
function func3(){ // 매개변수가 없는 함수
	document.write("<br>매개변수 갯수:",arguments.length);
	document.write("<br>매개변수 갯수:",arguments[0]+arguments[1]);
	}
func3();
func3(3,4);
func3(3,4,5);
func3("kbs","mbc");

function hap(){
	if(arguments[0] === undefined) return;
	
	let tot =0;
	for(let i=0; i<arguments.length; i++){
		tot+=arguments[i];
	}
	return tot;
}

document.write('<br>hap:',hap(1,2,3));
document.write('<br>hap:',hap("안녕","반가워"));
document.write('<br>hap:',hap());

(function(){
	document.write('<br이름이 없는 함수 : 익명함수');	
}) // 초기화 작업에 효과적

let abc = function(n1,n2){ // 함수 표현식
	document.write('<br>두 수의 합 : '+ (n1+n2));
} // 어노미너스 함수를 변수에 치환하여 사용
abc(2,3);

document.write('<br>선언적 함수와 함수표현식의 차이---');
var v1 = 10; // hoisting O
let v2 = 20; // hoisting X

func4(); // 호이스팅 기능으로 선언 전에 사용해도 가능
function func4(){ // 선언적 함수 이면서, script 실행 전 준비단계에서 전역으로 선언이 됨
	document.write('<br>선언적 함수 수행 (처음부터 메모리가 확보됨)');
}
func4();

// sbs(); // Uncaught ReferenceError 참조할 값이 없다, 유람
let sbs= function(){ // 함수 표현식 : 실행흐름이 해당 함수에 도달 했을 때 그때 함수를 실행
	document.write('<br>익명 함수 수행(휘발성, 단발성, 동적)')
}
sbs();

document.write('<br>중첩(내부) 함수 수행');
function func5(){
	document.write('<br>func5 수행 성공');
	function fu1(){
		document.write('<br>fu1 수행');
	}
	function fu2(){
		document.write('<br>fu2 수행');
	}
	fu1();
	fu2();
}
func5();
//fu1(); // 호출 안돼. 내부 함수는 외부에서 호출불가

function
func6(a,b){
	function innerfunc(x){
		return x * x;
	}
	return Math.sqrt(innerfunc(a)+innerfunc(b));
}
let re = func6(2,3);
document.write('<br>re : ',re);
document.write('<br>익명 함수 반환 -------');
function outer1(){
	document.write('와우! outer1');
	return function(){
		document.write('<br><i style="font:red;">익명 함수를 반환</i>')
	}
}
outer1()(); // 함수를 리턴받았으니 실행하려면 괄호 필요

function outer2(name){
	let msg="매력 덩어리 " + name;
	return function(){
		document.write('<br>'+msg);
	}
}
outer2("서호")();

document.write('<br>');
let tvn = function(arg1){
	let ytn = function(arg2){
		return arg1 * arg2;
	};
	return "결과는 " + ytn(arg1);
}
document.write('<br>'+tvn(3));


</script>
profile
같이 일하고 싶은 개발자가 되어야지

0개의 댓글