Gustavo
Gustavo

Reputation: 1683

Undefined is not a function error with "defined" argument

So this is a part of a simple JavaScript code to handle xmlhttprequest. The part that is generating the error is at the bottom (else if):

    httpReq.onreadystatechange = function(){
        if (httpReq.readyState == 4) {
            if (httpReq.status == 200) {
                var strRes = httpReq.responseText;
                if(xmlOrig) strRes = (new $Xml(strRes, true)).conteudo(xmlOrig);
                if(elemDest) $id(elemDest).innerHTML = strRes;
                if(func) {
                    var dadosArray = new Array(4, strRes, httpReq, 'OK', 'Concluído com sucesso.');
                    window[func](dadosArray);
                }
            } else {
                if(elemDest) elemDest.innerHTML = 'Erro: '+httpReq.status+' | '+httpReq.statusText;
                if(func) {
                    var dadosArray = new Array(4, false, httpReq, 'erro', 'Erro, conteúdo não carregado!');
                    window[func](dadosArray);
                }
            }
        } else if(func){
            console.log("func? "+typeof(func));
            var dadosArray = new Array(httpReq.readyState);
            window[func](dadosArray);  // <-- HERE IS THE ERROR!
        }
    }

However, the console.log return the "func" argument as a function, so where is the error?

The Safari console:

func? function TypeError: 'undefined' is not a function (evaluating 'windowfunc')

Upvotes: 0

Views: 128

Answers (2)

apsillers
apsillers

Reputation: 116060

You probably meant to do window["func"] instead of window[func].

The latter expression is equivalent to window["function(someParam) { ... }"] (i.e., a whatever the content of func actually is). window probably does not have a property whose name is the entire stringified text content of func.

Upvotes: 1

wesbos
wesbos

Reputation: 26317

Are you sure func is on the window? You are checking for func, which could be inside any scope, and thne you can calling window.func().

Upvotes: 1

Related Questions