The meaning of “This” and “That” in Javascript

Intro

In Javascript “this” is a special keyword which often confuses developers. You’ll often see a variable of “that” within methods which have a value of the mysterious “this” Discussing the meaning of “this” might sound philosophical, in Javascript “this” is actually not as ambiguous as it seems. In short:

“this” is a reference point to what is calling a function. It’s a reserved Javascript keyword

“that” is a variable used to to pass scope to private methods. It’s not part of the language but is a popular Javascript “design pattern” (which makes up for what many believe is an error in the Javascript specification).

The “this” keyword explained

Using this is very handy when referring to values within an object. Understanding how it’s use is essentially to writing clean, efficient code. Let’s look at the usage of the this keyword in practice.

var ourFunction = function () {
	console.log(this);
};
ourFunction(); 

What this will do is log the Window object to our console. This is because ourFunction() is being called from the root, or the Window object in your browser.

Lets call this from within an method inside another object.

var ourObject = {}

ourObject.ourMethod = function(){
	console.log(this);
}
ourObject.ourMethod()

this is no longer the Window object. It’s ourObject, since that’s what’s calling it. Or as the MDN puts it:

“Use the this keyword to refer to the current object. In general, this refers to the calling object in a method”.

Don’t be confused by the word “this”

I find the word “this” little counter intuitive. If I were to say “THIS is my house” while standing inside my actual house, by Javascript logic, my house would belong to the root, Earth.

If I were to wrap my house inside a my city, my house would belong to the city, since that’s what’s calling it.

var newYork = {}

newYork.myHouse = function(){
	console.log(this);
	console.log("is my house");
}

newYork.myHouse();
// Object {myHouse: function}. I guess New York actually owns my house. Bummer.

Why we use “that”

You might run into a few problems when trying to pass defined values …

Read More»

PubSub in Javascript

If you’re working on a large app, it’s important that all your system remains flexible. Nothing is worse than coding yourself into a corner. One of my favorite Javascript design patterns is PubSub. Go ahead and say that out loud a few times. It’s got a nice flow to it doesn’t it?

Intro

PubSub, which is short of Publish Subscribe (which is not nearly as fun to say), is a way of “decoupling” your code. Basically one method publishes, messages such as objects, and another method subscribes to it. It’s beauty is in it’s simplicity.

“In software engineering, coupling or dependency is the degree to which each program module relies on each one of the other modules.”- Wikipedia

Try to avoid coupling in your Javascript applications. PubSub lets you send whatever message you wish to whatever listening, without having to sorry about scope. (The communication flow reminds me of an old fashioned radio broadcast).

pub("dance", "hustle");

var danceVar = sub('symbolMethod', function(obj) {
	if (obj === "hustle") alert ("Do the hustle!");
});

Whenever you broadcast on the “dance” channel, whatever is subscribed to that will receive it.

broadcast = (function() {  
    var topics = {};
    return {
        sub: function(topic, listener) {
            if (!topics[topic]) topics[topic] = {
                queue: []
            };
            var index = topics[topic].queue.push(listener) - 1;
            return {
                remove: function() {
                    delete topics[topic].queue[index];
                }
            }
        },
        pub: function(topic, info) {
            if (!topics[topic] || !topics[topic].queue.length) return;

            var items = topics[topic].queue;
            items.forEach(function(item) {
                item(info || {});
            });
        }
    };
})();

Is this like DOM events?

Similar in concept, but different. PubSub is similar in that it’s an action triggered by an event, but has nothing to do with the DOM or event methods. This makes it an extremely useful pattern if you’re working without a DOM like with Node.

More Recourses

There are a TON of PubSub libraries out there. I think it’s faster to write my own than to learn someone else’s library. But if you want more features, you have many to choose from.

For more Pub Sub, David Walsh has a great article here

If you have a half hour, …

Read More»

The Module Pattern

The great thing about JavaScript is you can make up your own structure. The awful thing about JavaScript is everyone makes up their own structure. (kidding).

One my my favorite design patterns for keeping things organized is what’s called the “Module Pattern”. I’m a fan of keeping things as simple as possible, and the Module Pattern let’s you write very clean, decoupled code, without over complicating things.

Creating a Module

Creating a Module begins with an IIFE or an immediately-invoked functional expression. It’s basically a function wrapped in an extra paren which lets the function execute itself. This is known as a function expression. Everything that happens inside of it are kept private from the parent scope. I’ll explain why thats awesome in a minute.

// an IIFE
(function(){
	// code
})()

To declare it as a module, simply give it a name space like this:

// a module function
var awesomeModule = (function(){
	// code
})()

Privacy

One of the fantastic things about the Module pattern is how easy it is to implement privacy in you object. Privacy basically means that what happens in your object, stays in your object, unless told otherwise.

var awesomeModule = (function(){
	var thisVar = "foo";
	function _privateMethod (){
		// code
	}
	return {
		var publicMethod = function(){
			return thisVar;
		}
	}
})()


alert(thisVar) // undefined
alert (awesomeModule.pubicMethod()) // foo

In the example above thisVar is not exposed outside of awesomeModule until the publicMethod() is ran. It’s encapsulated within the object, making it a Private variable.

Historically Javascript has not been given the same respect as some other languages associated with object-oriented programming. But when used properly, such as taking advantage of encapsulation, Javascript can be just as powerful as it’s peers.

The Module Pattern in Practice

I use the Module Pattern whenever I have data I don’t want to directly expose (such as values within a game). Traditionally encapsulation is synonymous with security but on client side Javascript everything you have to be careful what you calculate on the browser. In a more secure environment (like on a server), the security …

Read More»