rss
logo
 

"It is the mark of an educated mind to be able to entertain a thought without accepting it."  -Aristotle

About Me

I am a co-founder of Notches, a distributed platform for reviews. You can find out more on our official blog.

Read more about my background.

Connect with me on...

Javascript Syntax

Warning:

This article is more than 45 days old and thus may be somewhat out of date. Please keep this in mind when reading the post. If this is a tutorial, please check whether you are using the same versions mentioned in the article.

I've worked with JavaScript extensively over the past few years. Actually, I would say I'm way too intimate for my own sanity, but that's another story. JavaScript isn't a true object-oriented language, because there is no real concept of inheritence and protection. Rather, every object is just a hash-table, where the keys are pointers to either a method or property or object. It actually proves to be quite powerful - declaring and repointing methods at runtime is always pretty neat.

I enjoy seeing others (Darren, Andy) dig into the possibilities of JScript, as Darren and Andy are.

One cool thing, as Andy showed in his code, is that every property or method can be enumerated either by index or key name.

Also, if you ever need to be able to resolve what method you're in, I wouldn't recommend using anonymous functions - use something with a meaningful name instead that you can parse and make sense of.

Scoping is also quite interesting in JavaScript.

First of all, presumably for performance reasons, the only scope block that JavaScript recognizes is the function. So declaring and defining a variable within an if block does not change the scope.

Let's take an example Faisal encountered recently.

 

function xyz()
{
if( some condition )
{
var foo = 'Hello World\n';
}

if( some other condition )
{
// Is foo available here?
alert( foo );
}
}

 

Of course, it is, but that's somewhat counter-intuitive, right?

Another thing I find quite interesting is that a function is actually just an object, and it too has methods. And a method on an object is just a pointer to the object. When you use the object.method() syntax, you're basically taking the method function reference and calling the apply method, passing in object to act as the scope. You can do this yourself, btw, taking a function and passing in the “this“. Cool, huh?

Actually, the whole “function.apply“ stuff can be a bit unsettling at times, but it too is pretty powerful.


Powered by Community Server (Non-Commercial Edition), by Telligent Systems