JavaScript Closures – The Absolute Basics: Getters and Setters

The next step in mastering JavaScript closures is being able to “get” or “set” a private variable

In Part I of this series: JavaScript Closures – The Absolute Basics, I discussed wrapping one function with another, which produces a closure. When that returned function is assigned to a variable, as long as that variable is alive, it (a function) has access to the context of the function that wraps it. This means that the outer (or “wrapping”) function can contain a private member, but the wrapped function has access to it. In that post, the example code consisted of a function that returned the private member.

Let’s take this one step further: we want to be able to “get” and “set” that private member in real time. Consider the following code:

Example # 1

Here is the JsFiddle link: http://jsfiddle.net/a6LBf/

In example # 1, we first create a global variable named “drink” that is set equal to “wine”. Why we did this will become apparent in a moment. next we have a variable named “foo”, which is set equal to an anonymous function. Here is where the “closure” stuff comes in: That anonymous function (i.e. “foo”) returns an object literal. That object literal contains two properties: “getDrink” and “seDrink”. Both are anonymous functions.

After the declaration of the anonymous function “foo”, we create a variable named “bar” that is equal to the return value of “foo” (i.e. we execute “foo”, and set the variable “bar” equal to that). Because “foo” returns an object literal, it is almost as if we simply did this:

But that does not completely represent what is going on here. Although “bar” is in-fact equal to an object literal that has two anonymous functions as members, that object literal was returned by a function (and that is a critical detail). Because that object literal was returned by a function, the two anonymous functions that are members of the object literal have access to the function that returned them. Because they will execute in the context of “foo”, they have access to the private scope of “foo”.

Ok, so what does this all mean?

Remember when we created a global variable named “drink”, and set it equal to “wine”. Well, in example # 1, when say: “console.log( drink )”, and the output is “wine”, that is because in the global context, “drink” equals “wine”. But there is another variable named “drink” in-play. That variable is in the private scope of “foo” and it is set equal to “beer”.

Hang in there, we are getting to the good stuff now

In example # 1, when we say: “console.log( bar.getDrink() )” and the output is “beer”, that is because “getDrink()” has access to the private scope of “foo”, and in the private scope of “foo”, “drink” is equal to “beer”. Next, when we say: “console.log( bar.setDrink(“juice”) )”, we are mutating (i.e. changing) the value of the variable “drink” that exists in the private context of “foo”. This is because:

  • “bar” was set equal to the value of whatever “foo” returned
  • “foo” returned an object literal
  • The object literal that “foo” returned contains a member: “setDrink()”
  • “setDrink()” has access to the variable “drink” which is in the private scope of “foo”
  • We change that private variable “drink” to “juice” using “bar.setDrink()”

If you run the jsfiddle link for example # 1, you will see this all in action (make sure you have your JavaScript console open). Once the code has run, type the following in your JavaScript console: “console.log( bar.getDrink() )” the return value will be “juice”.

Summary

There is no such thing as a wasted moment when it comes to understanding closures in JavaScript. This is a powerful feature of the language. In this post, we discussed getting and setting the value of a variable that exists in the private scope of a function that returned an object literal. Stay tuned for more to come on this topic which is at times seemingly complex, but more than worth the effort and an important tool in your JavaScript belt.

Understanding Scope in JavaScript

Although the ‘with’ statement creates a block-level scope effect, and recent implementations of the “let” statement have the same effect, these are fodder for another conversation. I’m not a big fan of the “with” statement, and at the time of this writing, you can’t be 100% sure that the “let” statement is fully supported by the user’s browser. The end result of this is the fact that there is no block-level scope in JavaScript. Scope is created by functions.

Example # 1

Here is the jsFiddle.net link for Example # 1 : http://jsfiddle.net/2ZkkR/

In Example # 1, we set the global variable “month” equal to “july”. But inside of the function “foo()”, we also create a variable named “month”, and give it a value of “august”. The second statement in foo() is a call to the console, telling it to output the value of the variable “month”.

So, why is it that in the global scope, “console.log(month)” outputs “july”, but executing “foo()” outputs “august” ?

The reason is that inside of the function “foo()”, we used the “var” keyword to create the variable “month”. When you use the “var” keyword, the variable you create becomes local to the function that you create it in. So, inside of “foo()”, the variable “month” is local, and equal to “july”. As a result, on the very next line, the statement: “console.log(month)” outputs “july”. Inside of “foo()”, we have no knowledge of the global variable “month”, because in the scope chain, the variable “month” is found locally, so the search for “month” ends within the local scope of “foo()”.

Example # 2

Here is the jsFiddle.net link for Example # 2 : http://jsfiddle.net/6TBEM/

In Example # 2, we have added a function named “bar()”. Bar does not have a local variable named “month”. So, when “bar()” executes, the statement “console.log(month)” kicks off a search for the variable “month”. In the scope chain, there is no local variable named “month”, so the JavaScript engine looks to the next level of the scope chain, which happens to be the global scope. In the global scope, there is a variable named “month”, so the value of that variable is returned, and it is “july”.

So, “foo()” outputs: “august” and “bar()” outputs: “july”, because, although they both look for a variable named “month”, they find completely different values; in their respective scope chains, the value of a variable named “month” differs.

Example # 3

Here is the jsFiddle.net link for Example # 3 : http://jsfiddle.net/ZaXxk/

In Example # 3, notice a new statement in the “foo()” function: “window.season”.

In this statement, we are creating a global variable named “season”. Although we are within the context of the “foo()” function, we can reference the global scope by mutating the “window” object. “window” is essentially the global object. Creating a global variable while inside of the local scope of “foo()” is easily done by adding a property to the “window” object; in our case we name it “season” and give it a value of “summer”.

So once again, although we are in the local scope of “foo()”, we have just created a global variable named “season” and given it the value of “summer”, by adding a new property to the “window” object (e.g., window.season = ‘summer’).

Example # 4

Here is the jsFiddle.net link for Example # 4 : http://jsfiddle.net/XYu4x/

In Example # 4, we create another global variable while within the local scope of “foo()”, named “weather”. This approach is different because when we say: weather = “hot”, the absence of the “var” keyword automatically makes the variable global. This is important to remember and make note of: If you omit the “var” keyword when creating a variable, no matter where you do it, that variable becomes global.

In general, this is something that you want to avoid, as it can lead to code that is hard to understand and even harder to maintain. But for the purpose of this discussion, it illustrates an important behavior in JavaScript: omitting the “var” keyword when creating a variable makes that variable global, no matter where you do it. I’m repeating this because it is an important detail to remember.

Example # 5

Here is the jsFiddle.net link for Example # 5 : http://jsfiddle.net/NTjYe/

In Example # 5, we yet again create a new global variable from within the local scope of “foo()”. This variable is named “activity”. We demonstrate yet another way in which you can do this by saying: this.activity = ‘swimming’. This introduces another concept: the meaning of “this” inside a function (no pun intended).

Inside a function, the “this” keyword refers to the context in which the function is executed. In our example, “foo()” is executed in the context of the global object, so “this” referes to the global object, which means that “this.activity” adds a property to the global object named “activity”.

Make note: While “foo()” has it’s own “local” scope, the keyword “this” refers to the context in which “foo()” is executed. This is another important detail to remember. It will come up a lot when writing more advanced JavaScript.

Another (very) important note:  An “implied global” is what occurs when you omit the “var” keyword when declaring a variable. There is a subtle, yet important difference between that and a variable created using the “var” keyword in the global scope: an implied global is actually not a variable; it is a property of the “window” object. For the most part, it behaves very much like a global variable, but there are differences: for example, you cannot delete a global variable, but you can delete a property of the window object. This is a topic worth looking into when you have time, and at minmum, good to be aware of.

Summary

At first, the concept of scope in JavaScript can be a challenge to fully understand. But it is very much worth the effort. Once you understand scope, the JavaScript language becomes a sharp knife that can be used to sculpt elegant and expressive code. This tutorial discussed only the most basic concept of scope in JavaScript. I highly recommend exploring it in-depth.

Helpful Links for Scope in JavaScript

https://developer.mozilla.org/en/JavaScript/Reference/Functions_and_function_scope/

http://coding.smashingmagazine.com/2009/08/01/what-you-need-to-know-about-javascript-scope/

http://oranlooney.com/function-scope-javascript/

How to Create a Name-Spaced Object to Avoid Using Global Variables in JavaScript

Creating your own custom Object is a good way to keep the global name-space clean and write organized code with predictable results.

Sometimes you may need variables that are available to every function in your script. While it is tempting to use global variables to achieve this kind of scope, doing so can cause unpredictable results and spaghetti code. If you create your own object, define your properties and methods, and then access them via a clean, name-spaced syntax, you control the scope as well as the code’s behavior.

Example # 1:

Here are a few examples of using global variables. In each case, it is very easy to lose track of the value of these variables throughout your script, as well as which functions have access to them.

You may want to access these variables from multiple functions in your code, and in various scenarios, change the value of those functions. This is certainly possible, but there are better ways to achieve the same functionality.

Example # 2:

In this example, we create a custom object called “bankClient”. We then define the properties of this object.

In this example, there are two ways that we could access these variables:

Example # 2A

  • object.property
  • object[‘property’]

Example # 2B

Either one of the above approaches will work just fine.

Example # 3:

You can also define a method for your object.  A method would be a function that you define within the object, and then call by using the same name-spaced syntax.  In the example below, we expand our object by adding a method. This method returns the value of the client account number.  You may notice the use of the “this” keyword. In such a case, “this” refers to the object who’s context we are currently in, which would be “bankClient”. This is something you’ll see often when working with objects in JavaScript.

That value is hard-coded in the object definition, but then  notice how we change the value of the property, and then retrieve it. In the same manner, the property “name” is at first empty, but we assign a value to it, and then grab that value (i.e. “Roger Sterling”).

The output for Example # 3 would be:

123456
Account # changed to: 111-222-333
Client Name: Roger Sterling

Summary:

Creating your own custom object is a good way to avoid cluttering up the global namespace. It is also an improved method of keeping tabs on your variables as they become properties of the object. You can define methods for your object and access them the same way. In doing this, you create organized code that’s easier to read, maintain, and extend.

Helpful Links about JavaScript Objects

http://www.w3schools.com/js/js_objects.asp

http://www.quirksmode.org/js/associative.html

http://www.javascriptkit.com/javatutors/oopjs.shtml