6 Advanced JavaScript Techniques You Should Know
This article doesn’t necessarily cover every detail of the methods I’m describing, but provides an overview, along with code examples, of some practical JavaScript coding techniques.
1. Closures to Extend Variable Scope
Closures in JavaScript are a fairly straightforward concept, and have been discussed online in a number of in-depth articles. The fact that they are straightforward doesn’t necessarily mean they’re simple however, as seen by the extensive articles that cover the subject.
“Think of closures as a kind of regional scope: broader than local but not as broad as global.”
To create a closure, you nest a function inside of a function. That inner function has access to all variables in its parent function’s scope. This comes in handy when creating methods and properties in object oriented scripts. Here is a simple example that demonstrates the use of a closure
function myObject() {
this.property1 = "value1";
this.property2 = "value2";
var newValue = this.property1;
this.performMethod = function() {
myMethodValue = newValue;
return myMethodValue;
};
}
var myObjectInstance = new myObject();
alert(myObjectInstance.performMethod());
Filed under Javascript by on Oct 9th, 2009.











Leave a Comment