JavaScript 에서 function 의 모든 매개 변수 이름 을 가 져 오 는 방법

2402 단어
함수 의 매개 변수 이름 을 해석 하기 위해 자 바스 크 립 트 함 수 를 썼 습 니 다. 코드 는 다음 과 같 습 니 다.

function getArgs(func) {
 //       ,            .
 //         : ([^)]*)          
 var args = func.toString().match(/function\s.*?\(([^)]*)\)/)[1];
 //         (arguments string).
 return args.split(",").map(function(arg) {
  //     (inline comments)    
  return arg.replace(/\/\*.*\*\//, "").trim();
 }).filter(function(arg) {
  //      undefined.
  return arg;
 });
}

위 에 검 측 된 함수 입 니 다. 예제 코드 는 다음 과 같 습 니 다.

function myCustomFn(arg1, arg2,arg3) {
 // ...
}
// ["arg1", "arg2", "arg3"]
console.log(getArgs(myCustomFn)); 

정규 표현 식 (regular expression) 이 좋 은 것 입 니까?다른 건 몰라 도 적당 한 장면 에 쓰 면 기 똥 차!
자바 가 현재 함수 이름 을 가 져 오 는 방법 을 추가 합 니 다: 자바 가 함수 에서 현재 함수 이름 을 가 져 옵 니 다.

public class Test { 
  private String getMethodName() { 
    StackTraceElement[] stacktrace = Thread.currentThread().getStackTrace(); 
    StackTraceElement e = stacktrace[2]; 
    String methodName = e.getMethodName(); 
    return methodName; 
  } 
  public void getXXX() { 
    String methodName = getMethodName(); 
    System.out.println(methodName); 
  } 
  public void getYYY() { 
    String methodName = getMethodName(); 
    System.out.println(methodName); 
  } 
  public static void main(String[] args) { 
    Test test = new Test(); 
    test.getXXX(); 
    test.getYYY(); 
  } 
}

[운행 결과]
getXXX  getYYY 
[주의]
코드 다섯 번 째 줄, stacktrace [0]. getMethodName () 은 getStackTrace, stacktrace [1]. getMethodName () 은 getMethodName, stacktrace [2]. getMethodName () 이 야 말로 getMethodName 을 호출 하 는 함수 이름 입 니 다.
/ / 주의: stacktrace 안의 위치; /[1] 은 "getMethodName" 이 고, [2] 는 이 방법 을 호출 하 는 method 입 니 다.

public static String getMethodName() { 
  StackTraceElement[] stacktrace = Thread.currentThread().getStackTrace(); 
  StackTraceElement e = stacktrace[2]; 
  String methodName = e.getMethodName(); 
  return methodName; 
}

이상 의 내용 은 본 고 에서 소개 한 js 가 function 의 모든 매개 변수 이름 을 얻 는 방법 입 니 다. 본 고 는 잘 쓰 지 못 했 으 니 양해 해 주 십시오. 여러분 의 귀중 한 의견 을 환영 합 니 다.

좋은 웹페이지 즐겨찾기