새소식

Front

[javascript] 간단하게 오버로딩 처리하기!

  • -
728x90

javascript는 오버로딩을 지원하지 않습니다.


예를 들어서,


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
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
 <head>
  <title> New Document </title>
  <meta name="Generator" content="EditPlus">
  <meta name="Author" content="">
  <meta name="Keywords" content="">
  <meta name="Description" content="">
 </head>
 
 <body>
  
<script>
    function test(content){
     alert(content);
    }
 
    function test(){
     alert(1);
    }
 
    test("hello my name is..");
</script>
 
 </body>
</html>
cs


결과는 아래와 같지요.


위에 작성된 function test(content){}는 무시당합니다.




해결하는 방법



solution : 1

파라미터 숫자로 구분하는 방법


1
2
3
4
5
6
7
8
    function test(){
        if(arguments.length === 1){
 
        }else if(arguments.length === 2){
 
        }
}
 
cs


solution : 2

typeof 키워드를 통해서, 자료형으로 구분하는 방법


1
2
3
4
5
6
7
8
9
    function test(){
        if(typeof arguments[1=== 'function'){
 
        }else if(typeof arguments[1=== 'boolean'){
 
        }else{
 
    }
}
cs


위 방법을 잘 활용하면

javascript 오버로딩을 적절히 해결할 수 있습니다. 감사합니다.




 

반응형
Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.