Understanding the difference between scope and context in a JavaScript method

JavaScript

scope and contextSometimes the concepts of scope and context are misunderstood in JavaScript. It is important to understand that they are not the same thing. This is particularly important inside of a method.

In JavaScript, the concept of scope refers to the visibility of variables. On the other hand, the concept of context is used to mean: “the object to which a method belongs”. That may sound like an odd statement, but it is accurate. The only time we care about context is inside a function. Period. Inside a function, the “this” keyword is very important. It refers to the object to which that function belongs. In other words, every function is a property of some object. In client-side JavaScript (i.e. in a browser), if you declare a function at the top of your code, then that function is a property of the window object. So, inside of that function, the “this” keyword refers to the window object. If you create a new object (let’s call it: “myObject”) and add a method (i.e. a property that happens to be a function), then inside of that function, the “this” keyword refers to the object (i.e. “myObject”).

So the main issue is that inside of a method, object properties and variables can sometimes be confused. In short; when the JavaScript “var” keyword is used, that is a variable. A variable will not be a property of an object (except in the global scope, which is for another discussion). But inside a method, any variable created using the JavaScript “var” keyword will be private to that method. So this means that it is not possible to access that variable from outside the method. But inside of a method, you have access to all of the properties of the object to which that method belongs. And you access these properties using the JavaScript “this” keyword. So, for example; if myObject.greeting = “Hello” and myObject.greet is a method, then inside myObject.greet, if I reference this.greeting, I should get the string: “Hello”. And if I have declared a variable named “speed” inside of myObject.greet, I would access it simply by referring to “speed” (i.e. I would not use the JavaScript “this” keyword). Also, a big difference between variables and properties in a method is that properties are always public. That is to say: all object properties can be seen and in most cases modified. But a private variable inside of a method is completely hidden from the outside world. And only our code inside of the method has access to that variable.

Try it yourself !

In above example, we start out by creating a property on the window object named: “foo”. This “foo” object is the result of an immediately invoked function expression (aka: “IIFE“). The reason that we take this approach is so that we can have a private variable: count. Our getCount method as access to that private count variable.

There is also a count property on the “foo” object. This property is available publicly. That is to say: we are able to make changes to the count property, whereas the count variable is not available outside of the IIFE. Our getCount method has access to the count variable, but that is the only way we can reach it.

When we call foo.getCount() without passing any arguments, then it increments the count property and returns it. This is CONTEXT. By using the JavaScript “this” keyword inside of the getCount method, we are leveraging the concept of context. Conversely, when we call foo.getCount(“scope”), then the count variable is incremented and returned. This is SCOPE. It is very important to understand the difference between scope and context in JavaScript.

The JavaScript “this” Keyword Deep Dive: Nested Methods

JavaScript

JavaScript LogoDepending on the scenario, the JavaScript “this” keyword may refer to the object of which the method is a property, or the window object.

In an earlier article: The JavaScript “this” Keyword Deep Dive: Nested Functions, we learned how functions that are not methods evaluate “this” to the window object. In that post, we demonstrated that no matter how deeply you nest functions, this behavior is always the same. In this article, we will learn how the JavaScript “this” keyword behaves in nested methods.

So, here, it might be a good idea to quickly answer the question: “What is a nested-method”?

A method is a function that is a property of an object. A nested method occurs when a method, in turn, returns an executed method.

The reason that this scenario is an important one to consider is that while you may execute method A, if that method returns the executed method of object B, then inside of that second method, the JavaScript “this” keyword refers to object B (not object A).

Example # 1

In Example # 1, we have added a property to the window object named “music”, and set the value to: “classical”. We have also added a method to the window object named “getMusic”, which returns the value of window.music. But, notice that instead of referencing window.music, the method returns: this.music. The reason that works is that since the method is a property of the window object, “this” refers to the window object. This means that this.music is the same thing as this.music, and the value of that property is: “classical”.

We have also created an object named “foo”, and it has the exact same-named properties we specified above, and the “getMusic” method has the exact same code: return this.music. But foo’s “getMusic” method returns “jazz”, because foo.music = “jazz”, which means that inside of foo’s “getMusic” method, the JavaScript “this” keyword refers to the foo object, and foo.music is “jazz”.

HERE IS THE JS-FIDDLE.NET LINK FOR EXAMPLE # 1: http://jsfiddle.net/5uUJ8/

Example # 2

In Example # 2, we have created an object named: “foo”, which has a method named: “getMusic”. The getMusic method returns an object with two properties: “music”, which is equal to “rock”, and “getMusic” which returns this object’s “music” property.

When we pass the output of foo.getMusic() to the console, we see that is: “rock”, and now “Jazz”. The reason for this is that foo’s getMusic method ignores foo’s music property. That is, it returns an object, and that object’s getMusic method returns its own “music” property. In this scenario, we have nested a method: foo.getMusic, that returns the executed method of another object. The reason for this example is to demonstrate the fact that even though foo.getMusic returns a nested method, when the nested method utilizes the JavaScript “this” keyword, it refers to the object that it is a property of, not foo.

HERE IS THE JS-FIDDLE.NET LINK FOR EXAMPLE # 2: http://jsfiddle.net/5uUJ8/1/

Example # 3

So, in Example # 3, we take the exact same approach as Example # 2, providing an additional level of method-nesting. As you might expect, the innermost method returns “metal”, the value of the “music” property to which the getMusic method belongs.

HERE IS THE JS-FIDDLE.NET LINK FOR EXAMPLE # 3: http://jsfiddle.net/5uUJ8/2/

Example # 4

Example # 4 is somewhat similar to Example # 3, except that the nesting is logical, not physical: each getMusic method, in turn, calls the getMusic method of a different object. The end result is the same as Example # 3: “metal”. But instead of one method returning an anonymous object whose getMusic method is executed, each of the getMusic method calls here return the execution of another named-object’s “getMusic” method.

It is also important to note that the first console.log call: this.getMusic returns “classical”, because the window.getMusic method is a property of the window object. But, each of the other objects (i.e. “rockObject” and “metalObject”) have its own “music” properties, so when the “metalObject.getMusic” is called, it returns the value of metalObject’s “music” property, which is “metal”.

HERE IS THE JS-FIDDLE.NET LINK FOR EXAMPLE # 4: http://jsfiddle.net/5uUJ8/3/

Summary

In this article we discussed how the JavaScript “this” keyword behaves inside of nested methods. We learned what a nested method is. And we also learned how, in this scenario, the JavaScript “this” keyword refers to the object of which the method is a property, not the window object.

Easy JavaScript Object Context Switching with jQuery.proxy()

jQuery

JavaScript LogoA popular saying in the Real Estate business is: “Location, location, location!” Well, in JavaScript, it’s all about “context”. When you want to leverage the very powerful keyword: “this”, then understanding the current context is critical.

So, those experienced with native JavaScript should be comfortable with the concept of context (If you are not, take a moment to brush up on this subject; it’s important.) When you need to specify context, you would normally use the .call() or .apply() methods. The jQuery folks have also provided a way to accomplish this with their .proxy() method. This method takes two arguments, which are: the function to be executed and the object whose context should be targeted. Any additional arguments are optional and are passed to the function that is executed.

Example # 1

In Example # 1, we have created two simple objects: “foo” and “bar”. Note that each object has one property named “music”. Next, we set up two click event handlers. In each case, we execute the “handler” function. And that function makes reference to “this”. If we were to run that function by itself, the output of the alert would be “undefined”, because when doing that, “this” refers to the window object, which at this time has no property named “music”.

So, by using the jQuery.proxy() method, we specify the context within which the “handler” function should be executed.

Here is the JS Fiddle link for Example # 1: http://jsfiddle.net/Shm47/

Example # 2

In Example # 2, we have taken our cause to the DOM. We first create a function named toggleColor, which when passed a class name, will toggle that class name.

Next, we set up two click event handlers. In each case, we leverage jQuery.proxy(), to call the “toggleColor” function, and specify the context within which it should run. We’re also specifying the class name to be passed to that function.

Here is the JS Fiddle link for Example # 2: http://jsfiddle.net/WzDUj/

Summary

In this article, we learned about the jQuery.proxy() method. In doing so, we discussed how it is used to specify the context within which a function should be executed. First we demonstrated how you can leverage this function using object literals. We then showed how you can do so by using DOM elements.

Helpful Links for the jQuery.proxy() method

http://api.jquery.com/jQuery.proxy/
http://stackoverflow.com/questions/3349380/jquery-proxy-usage
http://stackoverflow.com/questions/4986329/understanding-proxy-in-jquery
http://blog.kevinchisholm.com/javascript/context-http://blog.kevinchisholm.com/javascript/difference-between-scope-and-context/object-literals/
http://blog.kevinchisholm.com/javascript/difference-between-scope-and-context/

Getting to Know the JavaScript element.classList Object

Object-Oriented JavaScript

JavaScript LogoNative JavaScript provides a way to access and manipulate all of the CSS classes that are assigned to an HTML element.

The JavaScript element.classList object is an instance of the JavaScript DOMTokenList object. It exposes one property and a number of methods that allow you to work with CSS classes that are assigned to an HTML element.

While it has been supported for some time by all major browsers, Microsoft Internet Explorer has, unfortunately, ignored JavaScript’s element.classList object until very recently (what a big surprise). If you need to support IE9 and below (and of course you do), then all bets are off. Bummer. That said, this object is nonetheless a super-helpful feature that makes CSS class manipulation a snap.

But what about jQuery?

There is no doubt that the jQuery methods hasClass(), addClass(), removeClass() and toggleClass() are all fantastic, but there ain’t nothin’ goin’ on under the hood that you can’t do yourself. And what is under the hood is tedious stuff like this:

This kind of code will soon join the ranks of the eight-track cassette and pagers. While that is the current reality of cross-browser CSS class list manipulation, the fact is that native JavaScript is always evolving, and as soon as Internet Explorer 10 becomes the IE standard, the JavaScript element.classList object will be yet another native JS tool to tuck into your belt.

The length Property

Even though the element.classList object is not an array, it is “array-like” in that it has a “length” property, and each CSS class name is represented by a numerically indexed property whose value is the name of that class (a string). This is super-helpful if you want to enumerate the classes that are members of this object. You could certainly grab an individual member’s value using bracket-notation: element.classList[0], a “for” loop, or the item() method, which is discussed next.

The JsFiddle link below demonstrates the classList object’s length property. The class “bar” is toggled when you click the element specified. On each click, the classList object’s length property is shown. Since a class is toggled, that length value changes with each click, which helps to demonstrate the dynamic nature of this property. Keep in mind that like any JavaScript array, the length property’s value will always be one higher than the index of the last element.

Here is the JsFiddle.net link for the classList object’s “length” property : http://jsfiddle.net/BmFZc/

The item() Method

The item() method allows you to reference a specific class name in the collection of class names. When you pass an integer to this method, it returns a string representation of the class name that matches that index. So keep in mind that this collection is zero-based. In the first JsFiddle link below, we manually reference a number of classes in the class list, using the item() method. In the second JsFiddle link below, we use a “for” loop to accomplish the same task.

Here is the JsFiddle.net link for the item() method: http://jsfiddle.net/N88x9/

Here is a second JsFiddle.net link for the item() method: http://jsfiddle.net/WE7gc/

The add() method

As you might expect, the add() method adds a class to the element’s class list. In the JsFiddle link below, you can see that the class “bar” is added to the element’s class list because the element’s appearance changes dramatically, as per the CSS that is specified.

Here is the JsFiddle.net link for the add() method: http://jsfiddle.net/uzMAx/

The remove() Method

In the manner opposite to the add() method, the remove() method removes the specified class from the element’s class list. Much like the example for the add() method, you can see that the class “bar” is removed from the element’s class list because the element’s appearance changes dramatically, as per the CSS that is specified.

Here is the JsFiddle.net link for the remove() method: http://jsfiddle.net/4h7m4/

The toggle() Method

The toggle() method will check to see if the element already has the specified class. If not, then it adds the class. If it does have the class, then it removes it. Depending on the scenario, this can minimize redundant code.

Here is the JsFiddle.net link for the toggle() method: http://jsfiddle.net/wWfNf/

The contains() Method

You can check to see if an element already has a class by using the contains() method. When you pass it a string name representing the class that you would like to check for, it returns true or false, indicating whether or not the element has the class you provided.

Here is the JsFiddle.net link for the contains() method: http://jsfiddle.net/wWfNf/

The toString() Method

The toString() Method simply returns a space-separated list of the classes that are applied to that element.

Here is the JsFiddle.net link for the toString() method: http://jsfiddle.net/GqzD5/

Summary

In this article we learned about JavaScript’s element.classList object. We demonstrated that while not exactly a JavaScript array, it is an “array-like” object with a length property, and some useful methods that allow you to work with the CSS classes that are assigned to an HTML element.

Helpful Links for the JavaScript element.classList object

https://developer.mozilla.org/en-US/docs/Web/API/element.classList

http://blog.alexanderdickson.com/manipulating-classes-with-javascript

http://tiffanybbrown.com/2011/08/15/class-manipulation-with-classlist/

jQuery Plugin Authoring – The Absolute Basics – Part II

jQuery

jQuery LogoOnce you have jQuery plugin basics down, it’s time to implement some best practices

In the previous post “jQuery Plugin Authoring – The Absolute Basics – Part I”, we to a detailed look at the architecture of a jQuery plugin. Now that you understand the building blocks, let’s discuss a few best practices. These techniques are considered standard for quality jQuery plugin authoring, and will dress you for success.

Protecting the Dollar Sign

Most jQuery consumers associate the dollar sign with jQuery. But that dollar sign is simply a shortcut to the jQuery object, which is a property of the window object. You could write all of your jQuery code without ever using the dollar sign, and simply “jQuery” instead. But most people prefer the dollar sign because it is of course quite a bit easier and faster to type.

But jQuery offers a “no conflict” mode that allows another library to take over the dollar sign. It is considered best practice to anticipate this scenario and pass the global jQuery object into the immediate function that wraps your plugin. This way, inside of the nice and safe sandbox of your plugin, you can use the dollar sign all you like, without the slightest concern for how it is being used in the global context.

Example # 1

In Example # 1, we pass the global jQuery object into the immediate function. The immediate function takes that jQuery object as “$”, so from there on we are free to use the dollar sign safely, even if jQuery is in no-conflict mode.

Chainability

Method chaining is a popular technique in JavaScript. Many web developers use this technique when they leverage jQuery without even knowing it. How many time have you seen something like this:

$(SOME PARENT).find(SOME CHILD).CSS(“prop”,”val”).click();

What signifies the chaining activity is the fact that we have only one reference to the jQuery collection returned by $(SOME PARENT). Since each method used returns the jQuery object, we can use that return value to invoke another jQuery method, and so on. This is called “Chaining” method calls together.

It is considered best practice to allow method chaining when authoring your own jQuery plugin. Doing so is quite simple; you just need to return the jQuery object from each method.

Example # 2

In Example # 2, we return “this” from our plugin function. It’s important to note where the return statement is. Because the return statement occurs as the last line of code in our plugin’s function, the jQuery collection object is returned to the next method that wants to “chain”, without the need to re-state a jQuery collection.

Example # 3

In Example # 3, we have an example of method chaining in jQuery. Note that $(‘a’) only occurs once. That call to jQuery returns a jQuery collection object, which is returned from our jQuery plugin. As a result, the .attr() method can “chain” onto that return value and function properly.

Example # 4

In Example # 4, we have an even more complex example of method chaining. First we invoke “myPlugin”, and the the jQuery methods: .attr(), .css() and .click()

Here is a fully working JSFiddle.net link that demonstrates the best practices we have covered in this article. Be sure to click a few of the links to demonstrate the method chaining from example # 4:

http://jsfiddle.net/fTA95/

Summary

In this article we discussed a few jQuery plugin authoring best practices. We covered how to safely use the dollar sign in your plugin code, even when jQuery is in no-conflict mode. We also covered how to implement method chaining.

Helpful Links for jQuery plugin authoring

http://docs.jquery.com/Plugins/Authoring
http://stackoverflow.com/questions/12632382/jquery-plugin-authoring-and-namespacing