The JavaScript “this” Keyword Deep Dive: Constructor Functions

JavaScript

JavaScript LogoLearn how the JavaScript “this” keyword differs when instantiating a constructor (as opposed to executing the function).

In earlier articles of the “The JavaScript “this” Keyword Deep Dive” series, we discussed how the meaning of “this” differs in various scenarios. In this article, we will focus on JavaScript constructors. It is critical to keep in mind that in JavaScript, constructor functions act like classes. They allow you to define an object that could exist. The constructor itself is not yet an object. When we instantiate that constructor, the return value of the instantiation will be an object, and in that object, “this” refers to the instance object itself.

So, inside of a constructor function, the JavaScript keyword refers to the object that will be created when that constructor is instantiated.

Example # 1

In Example #1, you’ll see that we have created two new properties of the window object: “music” and “getMusic”. The “window.getMusic” method returns the value of window.music, but it does so by referencing: “this.music”. Since the “window.getMusic” method is executed in the global context, the JavaScript “this” keyword refers to the window object, which is why window.getMusic returns “classical”.

When you instantiate a JavaScript constructor function, the JavaScript “this” keyword refers to the instance of the constructor.

We’ve also created a constructor function named “Foo”. When we instantiate Foo, we assign that instantiation to the variable: “bar”. In other words, the variable “bar” becomes an instance of “Foo”. This is a very important point.

When you instantiate a JavaScript constructor function, the JavaScript “this” keyword refers to the instance of the constructor. If you remember from previous articles, constructor functions act like classes, allowing you to define a “blueprint” object, and then create “instances” of that “class”. The “instances” are JavaScript objects, but they differ from object literals in a few ways.

For an in-depth discussion of the difference between an object literal and an instance object, see the article: “What is the difference between an Object Literal and an Instance Object in JavaScript? | Kevin Chisholm – Blog”.

Earlier on, we established that inside a function that is not a method, the JavaScript “this” keyword refers to the window object. If you truly want to understand constructor functions, it is important to remember how the JavaScript “this” keyword differs inside that constructor. When you look at the code, it seems as if “this” will refer to the window object. If we were to simply execute Foo as if it were a normal function, this would be true (and we will discuss this scenario in Example # 3). But we don’t simply execute Foo; we instantiate it: var bar = new Foo().

When you instantiate a JavaScript constructor function, an object is returned. The JavaScript “this” keyword has a special meaning inside of that object: it refers to itself. In other words, when you create your constructor function, you can use the “this” keyword to reference the object that WILL be created when the constructor is instantiated.

So, in Example # 1, the getMusic method returns “this.music”. Since the “music” property of Foo is: “jazz”, then the getMethod returns “jazz”. When we instantiate Foo, the variable “bar” becomes an instance of Foo, so bar.getMusic() returns “jazz”.

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

Example # 2

In Example # 2, we have changed Foo’s “GetMusic” method. Instead of returning “this.music”, it returns an executed function. While at first glance, it may seem as though the “getMusic” method will return “jazz”, the JSFiddle.net link demonstrates that this is not the case.

Inside of the “getMusic” method, we have defined a variable that is equal to an anonymous function: “myFunction”. Here is where things get a bit tricky: “myFunction” is not a method. So, inside that function, the JavaScript “this” keyword refers to the window object. As a result, that function returns “classical” because inside of “myFunction”, this.music is the same thing as window.music, and window.music is “classical”.

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

Example # 3

In Example # 3, we have an example of a scenario that you don’t want: executing a JavaScript constructor function instead of instantiating it. Hopefully, this is a mistake that you will catch quickly, but it can happen. It is also possible that you might inherit code that contains such a bug. Either way, this is bad.

While the Foo constructor still has a “getMusic” method, because we execute Foo, instead of instantiating it, the code inside of Foo overwrites two properties that we created earlier: window.music and window.getMusic. As a result, when we output the value of “this.getMusic()”, we get “jazz”, because when we executed Foo, we overwrote window.music, changing it from “classical” to “jazz”.

While this is a pattern that you want to be sure to avoid in your code, it is important that you be able to spot it. This kind of bug can leave you pulling your hair out for hours.

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

Summary

In this article we learned how the JavaScript “this” keyword behaves in a constructor function. We learned about instantiating a constructor and the relationship between “this” and the instance object. We also discussed a couple of scenarios that are important to understand with regards to “this” and constructor functions.

The JavaScript “this” Keyword Deep Dive: Nested Functions

JavaScript

JavaScript LogoLearn how the JavaScript “this” keyword behaves inside of function declarations and expressions, even when nested 10 levels deep.

In the article: The JavaScript “this” Keyword Deep Dive: An Overview, we discussed a number of scenarios in which the JavaScript “this” Keyword has different meanings. In this article, we will concentrate on functions and methods.

It’s important to note that methods are functions. What makes a method a method is that the consumer of the code specifies an object, and then calls a method of that object.

Example # 1

In Example # 1, we have executed a function and a method. We have actually executed two functions, but the second function: “someMethod” is actually a method of the “bar” object. We know this because we have used the syntax: object.method().

It’s important to understand the difference between executing a function and a method.

Example # 2

foo = function (){ return this.music; }; console.log(this.music); //’classical’ (global) console.log(foo()); //’classical’ (global)

HERE IS THE JS-FIDDLE.NET LINK FOR EXAMPLE # 2: http://jsfiddle.net/84Yd4/

In Example # 2, we have executed the function “foo”, which returns the value of “this.music”: “classical”. Both console.log statements return the value: “classical”, because since we are not inside of a method, the JavaScript “this” keyword refers to the window object, and at the top of the code, you’ll see that window.music is equal to “classical”.

Example # 3

foo = function (){ function bar(){ function baz(){ function bif(){ return this.music; } return bif(); } return baz(); } return bar(); }; console.log(this.music); //’classical’ (global) console.log(foo()); //’classical’ (global)

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

In Example # 3, things get a bit silly, but the effect is the same. Even inside of nested functions, because none of these functions are methods, the JavaScript “this” keyword refers to the window object. And “this.music” is the same as “window.music”, which is equal to “classical”.

Example # 4

foo = function (){ function bar(){ function baz(){ function bif(){ function billy(){ function bobby(){ function betty(){ function jetty(){ function jimmy(){ function judy(){ return this.music; } return judy(); } return jimmy(); } return jetty(); } return betty(); } return bobby(); } return billy(); } return bif(); } return baz(); } return bar(); }; console.log(this.music); //’classical’ (global) console.log(foo()); //’classical’ (global)

In Example # 4, the function-nesting concept is taken to a ridiculous level. Nonetheless, the output is exactly the same: “this.music” is the same as “window.music”, which is equal to “classical”. It does not matter how deeply a function is nested. Unless it is a method of an object, the JavaScript “this” keyword will always refer to the window object.

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

Summary

In this article we learned that when a function is not specified as a method of an object, the JavaScript “this” keyword refers to the window object. This is true even in the case of nested functions. In fact, no matter how many levels deep we nest functions, the JavaScript “this” keyword refers to the window object.

The JavaScript “this” Keyword Deep Dive: An Overview

JavaScript

JavaScript LogoLearn the subtle yet critical details that allow you to leverage the JavaScript “this” keyword.

In JavaScript, the “this” keyword is one of the most overly-used yet under-utilized aspects of the language. It is also one of the most mis-understood topics. While it facilitates more readable, expressive object-oriented JavaScript, improper use is a catalyst for confusing code that is difficult to debug.

Personally, I’ve struggled to understand the mystery. I’ve heard many unusually long-winded explanations, which I feel only contribute to the silliness. Simply put: In JavaScript, “this” refers to the object upon which a function is invoked. That’s it.

In JavaScript, “this” refers to the object upon which a function is invoked.

This means that “this” can only be used in a function, or globally. When used in either of these cases, “this” refers to the window object. When the function is a method of an object, then “this” refers to the object that the method is a member of. When the function is a constructor, then “this” refers to the instance object. There is much more to talk about with regards to what “this” means in varying scenarios, but these are the most common situations.

Example # 1

In Example # 1, we have added a property to the window object, named it: “music”, and assigned the value “classical”. In the line that follows, we output the value of “this.music”, and the result is: “classical”.

The reason for the output is simple: If you execute arbitrary code in the global context (i.e. outside of a function), then “this” refers to the window object. Executing arbitrary code in the global context is highly discouraged, but it is important to understand this behavior from a theoretical standpoint; in the global context: “this” will evaluate to the window object.

Example # 2

In Example # 2, we have added a function named foo, and then logged the output of that function’s execution. The resulting value is: “classical”. Some may have expected the output to be “blues”. This is a common mistake.

In the function “foo”, “music” is a variable. The “this” keyword has to do with objects, never variables (there is a very subtle scenario where “this” refers to a variable, which we will address in a later post). So the fact that there is a variable named “music” is completely meaningless in this example. The function “foo” does only one thing: it returns the value of this.music. In that function, “this” is the widow object, and the value of window.music is: “classical”. So, the variable “music” is completely ignored.

Example # 3

In Example # 3, we have added an object named “bar”. This object has two properties: “music”, which has a value of “jazz” and “getMusic”: a method that returns the value of bar’s “music” property.

The “getMusic” method has a line of code that you have seen in previous examples: “return this.music”. But why does that line of code return: “jazz”? The reason for this behavior is that when a function is a method of an object, the “this” keyword refers to the object upon which that function is invoked. In this case, the object is “bar”, and bar’s “music” property is equal to “jazz”, so “this.music” is equal to “jazz”.

Example # 4

In Example # 4, we have added the constructor function: “Baz”. “Baz” has a property named “music”, and it is equal to “rock”. It also has a property named “getMusic”, which is a method. The “getMusic” method returns the value of Baz’s “music” property.

You may be thinking that inside of the “Baz” constructor, the “this” keyword refers to the window object, as discussed in Example # 2. If we were to simply execute “Baz” (e.g. Baz() ), then yes, the property window.music would be overwritten and given the value of “rock”, and there would be a new global property named “getMusic”, which would return “rock”.

But that’s not what happens. After we create the constructor: “Baz”, we instantiate it, which results in a variable named “bif”, an instance of “Baz”. When you instantiate a JavaScript constructor function, the “this” keyword inside of that function refers to the instance object that the constructor returns.

HERE IS THE JS-FIDDLE.NET LINK

FOR EXAMPLE # 3:

Summary

In this article we discussed the high-level details of the JavaScript “this” keyword. We learned that it refers to the object upon which a function is invoked, and how it means different things in different scenarios. The scenarios we covered are: the window object, inside of a function, inside of a method, and inside of a constructor function.

Creating an HTML Option Element Using the JavaScript Option() Constructor

JavaScript

JavaScript LogoThe little-known JavaScript Option() constructor allows you to avoid the verbose syntax of creating DOM elements

We all love jQuery. Among the many awesome qualities of this library is the ability to easily create DOM elements and place them in the document without the normally verbose syntax of native JavaScript.

But there is a little-known feature of JavaScript that allows you to create option elements with fairly minimal effort. This feature is the Option() constructor. The syntax is simple:

  1. Get a reference to a form element
  2. Instantiate the constructor and associate the returned object with the form element
  3. During instantiation, pass-in the following arguments: 1) the text shown in the page [string], 2) the value of the control [string], 3) if it is the default selection [true/false] and if it is selected [true/false]

Example # 1

 

In Example # 1, we have a simple form that includes a select control. In the markup there are three options: “Monday”, “Tuesday” and “Wednesday”. When the JavaScript runs, the following actions take place:

  1. We get a reference to the select controls (“w”)
  2. We delete all of the option elements (w.length = 0)
  3. We create an array of objects, each with two properties (“d”)
  4. We loop through the array and for each array element, dynamically create a new select element, using the object’s “text” and “val” properties. In each case the last two arguments: “false”,”false” mean that this new element will not be the default, nor will it be selected.

And that’s it!

Summary

The little-known Option() constructor can be used to create new HTML option elements. So, depending on how you choose to approach this, you can write some pretty efficient code that side-steps the normally verbose syntax of document.createTextNode(), document.createElement(), and document.appendChild() methods.

Helpful Links for the JavaScript Option() constructor

http://www.coderanch.com/t/120551/HTML-CSS-JavaScript/Option-Constructor

http://www.devguru.com/technologies/ecmascript/quickref/option.html

http://msdn.microsoft.com/en-us/library/ie/dd757810(v=vs.85).aspx

JavaScript Interview Questions: Object-Oriented JavaScript

Object-Oriented JavaScript

QUESTION:

True or False: the terms “scope” and “context” refer to the same thing in JavaScript.

Click for Answer

QUESTION:

If you omit the “var” keyword when creating a variable in a function, it becomes a property of what object?

Click for Answer

QUESTION:

How do you determine if a JavaScript instance object was created from a specific constructor or not?

Click for Answer

QUESTION:

True or False: Once you create an object, you can add, remove or change properties of that object at any time.

Click for Answer

QUESTION:

True or False: You can only instantiate a JavaScript constructor function once.

Click for Answer

QUESTION:

When you create a function inside of a method, what does the “this” keyword refer to when used in that function?

Click for Answer

QUESTION:

Name two ways two change the context of a JavaScript method

Click for Answer

QUESTION:

Can a JavaScript constructor return a primitive value (e.g. a number or a string)?

Click for Answer

QUESTION:

In JavaScript, are objects passed by reference or by value?

Click for Answer

QUESTION:

What is the difference between a constructor function and a non-constructor function with respect to the word “this”

Click for Answer

QUESTION:

What is the name of the property that allows you to add properties and methods to an object, as well as every object that inherits from it?

Click for Answer

QUESTION:

True or False: An object literal can be used to create private variables.

Click for Answer

QUESTION:

What is the name of the object that refers to the application used to view a web page?

Click for Answer

QUESTION:

True or False: The object returned by the document.getElementsByTagName() method is an array.

Click for Answer


QUESTION:

Which object.property combination provides a reference to the protocol used to view the current web page?

Click for Answer

QUESTION:

Given the below code, what line of JavaScript would allow foo.getColor to return the value of foo.color, without using the word “foo”?

Click for Answer (+)

QUESTION:

What is the difference between using dot notation and bracket notation when accessing an object’s property?

Click for Answer (+)

QUESTION:

What is important to remember about the last property’s value in a JavaScript object literal?

Click for Answer

QUESTION:

Given the following code, what is very likely the reason that the programmer made the first letter of “Foo” a capital letter?

Click for Answer

QUESTION:

Given the following code, how would you instantiate the function “Foo” and assign it to the variable “bar”?

Click for Answer

QUESTION:

What are two ways in which the variable “foo” can be assigned to an empty object?

Click for Answer

QUESTION:

True or False: When you create an object literal, you must first instantiate the Object() constructor.

Click for Answer

QUESTION:

When using the addEventListener() method to create a click-handler for a DOM element, what is the value of “this” inside of the callback you specify?.

Click for Answer

QUESTION:

True or False: A JavaScript array is not an object

Click for Answer

QUESTION:

If a string is a primitive value, why does it have a split() method?

Click for Answer

QUESTION:

True or False: A function can have its own properties and methods.

Click for Answer