0

Uncaught TypeError: object is not a function

I decided to make my writeMessage() function anonymous; before it would always mess up when another instance of the writeMessage() function was created at the same time, causing text output to be jumbled (both messages being "wrote" would get put together and mixed up).

However, I've seen to have run into an error (as shown above). The variable object is a jQuery object (e.g: $('#myDivElement')).

Any ideas as to why this is? Thanks.

function writeMessage(message,object){
    (function(message,object,i){
        var self = this;
        setTimeout(function(){
            if(i < message.length){
                object.append(message.substr(i,1));
                i++; 
                self(message,object,i);
            }
        }, 25);
    }(message,object,0));
}
0

1 Answer 1

4
var self = this;

Since you are calling the function without context, self refers to the window object. window is an object (window.toString should give something like [object Window]) and not a function, so caling self(message,object,i) will not work.

Instead, use this:

var self = arguments.callee;
Sign up to request clarification or add additional context in comments.

7 Comments

Ah, thank you! It's working perfectly now. Didn't realize the this keyword referred to the window object in an anonymous function.
@user3029571 - The value of this has nothing to do with whether the function is anonymous or not. It has entirely to do with how the function is called and whether it's called in a way that sets this to something other than the global object. Since your function is not calling it in this way, this gets its default value.
@user3029571: Instead of arguments.callee you could also just give the function a name so that it'll work in strict mode where arguments.callee is prohibited.
@cookiemonster But that defeats the purpose of an anonymous function, does it not? Strict mode is for wimps who can't write proper code without the browser noping their face :p
No it does not. There's no particular "purpose" for it to be anonymous when you actually want to reference it. That's why we give a function a name, isn't it? Using arguments.callee provides no advantage, and is less portable.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.