[javascript] JavaScript에 함수가 있는지 확인하는 방법?

내 코드는

function getID( swfID ){
     if(navigator.appName.indexOf("Microsoft") != -1){
          me = window[swfID];
     }else{
          me = document[swfID];
     }
}

function js_to_as( str ){
     me.onChange(str);
}

그러나 때로는 내 onChange로드되지 않습니다. 다음과 같은 Firebug 오류

me.onChange는 함수가 아닙니다

이것이 내 프로그램에서 가장 중요한 기능이 아니기 때문에 정상적으로 저하되고 싶습니다. typeof같은 오류가 발생합니다.

그것이 존재하는지 확인한 다음 실행하는 방법에 대한 제안 onChange?

(아래의 방법 중 하나만 시도해보십시오)



답변

다음과 같이 해보십시오 :

if (typeof me.onChange !== "undefined") {
    // safe to use the function
}

또는 더 나은 아직 (UpTheCreek의 의견에 따라)

if (typeof me.onChange === "function") {
    // safe to use the function
}


답변

나는이 문제가 있었다.

if (obj && typeof obj === 'function') { ... }

obj가 정의되지 않은 경우 참조 오류가 계속 발생합니다.

결국 나는 다음을 수행했다.

if (typeof obj !== 'undefined' && typeof obj === 'function') { ... }

동료는인지 확인 나에게 지적 !== 'undefined'다음과 것은 === 'function'물론 중복됩니다.

더 간단하게 :

if (typeof obj === 'function') { ... }

훨씬 깨끗하고 잘 작동합니다.


답변

eval을 사용하여 문자열을 함수로 변환 하고이 evald 메소드가 존재하는지 확인하려는 경우 eval 내에서 typeof 및 함수 문자열 을 사용하려고합니다 .

var functionString = "nonexsitantFunction"
eval("typeof " + functionString) // returns "undefined" or "function"

이것을 바꾸지 말고 eval에 typeof 를 시도하십시오 . ReferenceError를 수행하면 다음이 발생합니다.

var functionString = "nonexsitantFunction"
typeof(eval(functionString)) // returns ReferenceError: [function] is not defined


답변

어때요?

if('functionName' in Obj){
    //code
}

예 :

var color1 = new String("green");
"length" in color1 // returns true
"indexOf" in color1 // returns true
"blablabla" in color1 // returns false

또는 귀하의 경우 :

if('onChange' in me){
    //code
}

MDN 문서를 참조하십시오 .


답변

시도 typeof'undefined'존재하지 않는 'function'기능 을 찾으십시오 . 이 코드에 대한 JSFiddle

function thisishere() {
    return false;
}
alert("thisishere() is a " + typeof thisishere);
alert("thisisnthere() is " + typeof thisisnthere);

또는 if :

if (typeof thisishere === 'function') {
    // function exists
}

또는 한 줄에 반환 값이있는 경우 :

var exists = (typeof thisishere === 'function') ? "Value if true" : "Value if false";
var exists = (typeof thisishere === 'function') // Returns true or false


답변

이것이 제안 된 것을 보지 못했다 : me.onChange && me.onChange (str);

기본적으로 me.onChange가 정의되지 않은 경우 (시작되지 않은 경우) 후자를 실행하지 않습니다. me.onChange가 함수이면 me.onChange (str)가 실행됩니다.

더 나아가서 할 수도 있습니다.

me && me.onChange && me.onChange(str);

나도 비동기 인 경우.


답변

//Simple function that will tell if the function is defined or not
function is_function(func) {
    return typeof window[func] !== 'undefined' && $.isFunction(window[func]);
}

//usage

if (is_function("myFunction") {
        alert("myFunction defined");
    } else {
        alert("myFunction not defined");
    }