The this variable is an important concept in JavaScript and in many Object-Oriented languages. (Technically this is a keyword, but that’s a minor point in understanding it.) The simplest way to think of this is that it references the object whose method is currently being called. (The harder, but more accurate, way of thinking of this is as a representation of the execution context, but I find that definition makes a person blink a lot while simultaneously scratching his or her head.) The brilliant Peter-Paul Koch describes this as the “owner” of the current method, which also works.

To put this into a context (double pun), take the following JavaScript code, which defines a custom object, representing a rectangle:

var r = {
    side1: 10,
    side2: 20,
    isSquare: function() {
        return this.side1 == this.side2;
    }
};

That code defines an object with two attributes and one method. The method, called using the code r.isSquare(), returns a Boolean value indicating if the rectangle is also a square or not. Since the isSquare() method is defined as part of the r object, within that method, this refers to r.

this in JavaScript Example

Now take this code:

function returnThis() {
    return this;
}

In JavaScript running within the Web browser, any function defined outside of any object becomes a method of the global window object. Thus, in that code, this refers to the global window object.

this in JavaScript Example 2

Those two examples explain the simplest implications of the this keyword. However, as of ECMAScript 5, JavaScript now has a strict mode, triggered by adding the string use strict to a page or function:

function someFunction() {
    'use strict';
}
It is recommended that you use strict mode, and I certainly do in my “[intlink id=”3016″ type=”page”]Modern JavaScript: Develop and Design[/intlink]” book.  But when  you run JavaScript in strict mode, this behaves a bit differently. The specific difference occurs within functions that are not associated with objects, as in the returnThis() example. In non-strict mode, this represents the global object in such cases, as just shown. In strict mode, this will be undefined, as the association between the function and the global object is not meaningful, even though it exists:
function returnThis() {
    'use strict';
    return this;
}

This change in behavior is fine, though, as a function that’s not overtly associated with an object really shouldn’t be called obliquely on the global object via this anyway. Put more simply: it’s best that code not rely upon the assignation of functions to the global object. If a function needs to use a global object, it should do so overtly, such as referring to window. And strict mode is really geared towards fixing these kinds of oddities and inconsistencies.

Taking this knowledge one step further, because this is undefined in strict mode in functions not associated with objects, you can use that fact to test whether or not your JavaScript is working in strict mode. To do so, just create a function not associated with any object and have it return a Boolean indicating whether or not this is undefined:

function isStrict() {
    return (typeof this == 'undefined');
}

This can be shortened to just returning the oppposite of this:

function isStrict() {
    return !this;
}

If this is undefined, which translates to false, then true (the opposite) is returned. If this refers to an actual object, that translates to the Boolean true, so false is returned.

If your code might need to know the strict mode in several places, you can assign that status to a variable, thereby only invoking the function once:

var strict = isStrict();

Or you can turn this all into an immediately-executed anonymous function:

var strict = (function() { return !this; }());

Obviously, using a function to report on the strict mode only works if the entire JavaScript file is or is not invoking strict mode.

And that’s how the this keyword behaves differently in JavaScript’s strict mode, and how you can use that modified before to test for strict mode, too.

On May 30, 2012, I’ll be speaking at the e-Commerce Conference and Expo in Istanbul, Turkey (note: the linked site is in Turkish, but if you view it in Google Chrome, for example, it will translate the pages for you). This is a one-day event, from 9:30 am until 5:00 pm. From 1:40 to 2:25, I’ll be presenting “Creating a Successful E-commerce Venture, or Failing Gracefully” as the conference’s technology session. At the end of this post is the presentation’s description.

If you’re in Turkey specifically, or nearby, I’d recommend you attend. And if anyone has any recommendations as to what I should do while I’m in Istanbul, please let me know!

Continue Reading…

One of the great qualities of HTML5 is that even though it has not been standardized yet, you don’t have to wait to use it. Well, if you’re prudent about what HTML5 features you use, that is. For example, in my “Modern JavaScript: Develop and Design” book, I use several of the new HTML5 form elements as they get treated as plain text elements on browsers that don’t support HTML5. Similarly, several new form attributes will be ignored by browsers that don’t recognize them. By adopting select HTML5 features, you can provide a better experience to those using better, current browsers, and rest assured that those using older browsers, or Internet Explorer, will still be able to use your site. The question, then, is what HTML5 features are safe to use and what ones are not?

One good resource for answering that question is HTML5 Please, created by the same brilliant minds that created the HTML5 Boilerplate and the Modernizr library. HTML5 Please covers HTML5, CSS3, and related technologies and while the information is good, the interface is even better. Through a single page and some sweet JavaScript, you can find out all you need to know. There’s a search box at the top and a series of demo filters you can use to quickly find the feature you’re thinking about using. These filters include specific versions of IE, support on mobile device, including older ones, and more. For example, you can quickly find out that the new date input type can be used with caution along with a “polyfill”. As defined by Remy Sharp, a polyfill is:

…a piece of code (or plugin) that provides the technology that you, the developer, expect the browser to provide natively.

So, for example, you can safely use the new HTML5 elements, such as footer, nav, and article, if you also use the html5shiv polyfill.

An alternative resource is When can I use… The interface isn’t as clean as HTML5 Please, but the site provides a lot of information and uses table to present most of its data. When can I use… covers CSS, HTML5, JavaScript APIs, SVG, and much more.

Let me know if there’s a good HTML5 resource that you’ve come to rely upon!

 

Peachpit Press has published online an article I wrote titled “The Five Biggest JavaScript Misconceptions“. This is one of three articles I wrote in support of my “[intlink id=”3016″ type=”page”]Modern JavaScript: Develop and Design[/intlink]” book. In the article, as the title states, I discuss what I believe are the five biggest JavaScript misconceptions, and by “biggest”, I mean both “popular” and “egregious”. It’s a quick read, so check it out. Thanks!

If you haven’t yet seen it, Steven O’Brien wrote an in-depth series of articles on the Yii framework’s component architecture, posted at phpmaster. In the series, O’Brien looks at the CComponent base class in detail. Every class in Yii is an extension of CComponent, so understanding what it brings to the table can be quite useful to the Yii developer. Part 1 looks at the classes key properties and methods. Part 2 discusses events. And part 3 explains the behaviors. If you’re using Yii, it’s worth reading these to better understand what’s going on at the fundamental level.