Javascript : Functions are Objects

Let’s talk about the different ways variables can work in Javascript. This stuff confused the heck out of me when I first started learning it, so I’m going to go over a lot of the different edge cases and try and give a more complete overview of what’s happening when you declare a variable.

What you should know going into Javascript is that it works differently than a typical object oriented language.

Everything in Javascript is an object (Functions are Objects)

This probably isn’t a surprise to you, or at least it’s probably not causing you to protest too much, especially if you’ve come out of C++ and are used to everything basically being an integer. But when I say that everything is an object, I don’t just mean in the backend.  I mean that you can treat everything like an object, all the time.

So where this changes things is in the way that you think about methods.

This looks and behaves pretty much the way you might expect it to in another language, other than the whole printing out the text of the function. But if that’s some type of internal magic, fine.  Nothing out of the ordinary, right?

Ok, now we’re getting a little bit weirder. Functions are objects, which means you can assign them to variables.  aVariable isn’t an instance of arnold, the function itself (stored in arnold) is being passed into the variable.

Now that we know that we can pass functions around to variables, we’re going to do something a bit weirder.

This ought to be throwing alarm bells off in your head.  Let’s go a bit farther into this ‘functions are objects’ thing.  Arnold is a variable, pointing to an object, which happens to be a function, and functions and objects are one and the same.

When I made that function, I was also declaring the variable arnold, and arnold as a variable is no different than any other Javascript variable. Which means that it can be reassigned, in this case to a new function.

Also, because javascript is weakly typed, I can do this, just to further drive the point home.

Incidentally, this is the reason you’ll sometimes see functions defined in two different ways.  Either way is acceptable.

There’s some more stuff to talk about in this area with the ‘this’ keyword and the way Javascript treats pointers and references, but that’s a subject for another post.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">