Zian's Blog

Scope and this in JavaScript

Today I want to talk a little about “scope” in JavaScript and the this variable. The idea of “scope” is that it’s where certain variables or functions are accessible from in our code, & the context in which they exist & are executed in.

Have you ever seen something like this?

function someFunction() {
	var _this = this;
	something.on("click", function() {
		console.log(_this);
	});
}; And wondered what the var _this=this; is all about, hopefully this article should clear it all up. The first scope is Global Scope. This is very easy to define. If a variable or function is global, it can be got at from anywhere. In a browser, the global scope is the window object. So if in your code you simply have:
var x = 9; You’re actually assigning the property window.x to 9 (when working in a browser). You could type window.x = 9; if you like, but because it’s the global object you don’t have to. Properties on the global object can be accessed from anyplace in our code.

The only other scope we can have is the Local Scope. JavaScript scopes at a function level. For example:

function myFunction() {
	var x = 5;
};
console.log(x); //nothing will show in console

Since x was initialized within myFunction(), it is only accessible within myFunction().

Caution!

If you declare a variable & forget to use var keyword, that variable is automatically made global. So this code will work:

function myFunction() {
	x = 5;
});
console.log(x); //5

This is really a very bad idea. It’s considered bad practice to clutter the global scope. You should add as fewer properties as you possibly can to the global object. That’s why libraries such as jQuery often do this:

(function() {
	var jQuery = { /* all methods go here */ };
	window.jQuery = jQuery.
})();

Wrapping the whole thing in a function which is then immediately invoked means all the variables within that function are bound to the local scope. At the very end you can then expose all your methods by binding the jQuery object to the window, the global object. Although I’ve simplified it hugely, this is in essence however the jQuery source works.

That’s pretty much all there is too it at a basic level. Things get a bit complex once we take a look at the this keyword in JavaScript and how it works. I’m sure we’ve all come across this issue:

$("someLink").on("click", function() {
	console.log(this); //points to someLink(as expected)
	$.ajax({
		//ajax set up
		success: function() {
			console.log(this); //points to the global object. Huh?
		}
	});
});

this is a variable that is automatically set for you once a function is invoked. The value it’s given depends on how a function is invoked. In JavaScript we have limited main ways of invoking functions. I don’t wanna talk about them all today, but just the three ways most people use them; either when a function is called as a method, or on it’s own, or as an event handler. Depending on how a function is invoked, this is set differently:

function bar() {
	console.log(this); //global object
};

myapp = {};
myapp.bar = function() {
	console.log(this); //points to myapp object
}

var link = document.getElementById("someId");
link.addEventListener("click", function() {
	console.log(this); //points to link
}, false);

Those are all fairly obvious. The MDN has a nice explanation for the third & why this happens. Go through!

There are few other ways in which we can invoke functions by explicitly defining what the value of this should be, but as this has already ended up as a quite long article, I’m leaving those for another day. If you have any questions, please do leave a comment & I will get back to you.

 

Exit mobile version