Tuesday, September 12th, 2006

Scope in Javascript

Category: Articles, JavaScript

Mike West has put some time into analyzing and understanding one of the more sticky issues in Javascript: scope.

Scope is one of the foundational aspects of the JavaScript language, and probably the one I’ve struggled with the most when building complex programs. I can’t count the number of times I’ve lost track of what the this keyword refers to after passing control around from function to function, and I’ve often found myself contorting my code in all sorts of confusing ways, trying to retain some semblance of sanity in my understanding of which variables were accessible where.

He has published his explorations as an article in Digital Web Magazine. In it he deals with the basics of scope; the this keyword in method calls, constructors, function calls and event handlers; the apply() and call() methods; and Prototype’s bind() extension to Function.

The article is illustrated throughout with code examples and includes a list of useful references at the end. A good addition to the family of online Javascript resources.

Posted by Dietrich Kappe at 1:45 pm

4.2 rating from 42 votes


Comments feed TrackBack URI

Indeed a very clear and enlightening piece about Javascript scope.

Anyone who uses Prototype on a daily basis and doesn’t have an exact idea just what the hell function.bind(obj) does (except fixing your scope mostly) should read it for a clear explanation.

Comment by Alex — September 12, 2006

Very good article. Even if you have a firm grasp on scope it never hurts for a lil’ refresher. I dig his analogies as well.

Comment by Mario — September 13, 2006

Leave a comment

You must be logged in to post a comment.