JavaScript Quiz #1

Having quizzes from time to time is very important in order to refresh our information. This is why I decided to post JavaScript quizzes in order to have a better understanding of JavaScript.

Assume that we have the following JavaScript code:

var someVar = 1;
var someObject = {
	someVar: 2,
	someMethod: function () {
		var someVar = 3;
		
		alert(this.someVar); //What is the result ???
		
		setTimeout(function(){
			alert(this.someVar); //What is the result ???
		}, 10);		
	}
};

someObject.someMethod();

The question is what is the output in each alert and Why?
.
.
.
.
.
.
.
.
.
.
.
.
.
In order to understand how this JavaScript example will work, we should know how the JavaScript “this” keyword works. It is important to know that within a body of JavaScript method, “this” evaluates to the object on which the method was invoked.

This mean in the “this.someVar” expression of the first alert, “this” will be evaluated to someObject object on which someMethod method was invoked, which will result in 2 (the value set in line 3).

In the “this.someVar” expression of the second alert, “this” will be evaluated to Window global object because of the window.setTimeout, which will result in 1 (the value set in line 1).

This is all about this quiz. Stay tuned for the next one soon!

This entry was posted in JavaScript and tagged , , , , by Hazem Saleh. Bookmark the permalink.

About Hazem Saleh

Hazem Saleh has more than eleven years of experience in Cloud, Mobile and Open Source technologies. He worked as a software engineer, technical leader, application architect, and technical consultant for many clients around the world. He is an Apache PMC (Project Management Committee) member and a person who spent many years of his life writing open source software. Beside being the author of the "JavaScript Unit Testing" book, "JavaScript Mobile Application Development" book, "Pro JSF and HTML5" book and the co-author of the "Definitive guide to Apache MyFaces" book, Hazem is also an author of many technical articles, a developerWorks contributing author and a technical speaker in both local and international conferences such as ApacheCon North America, Geecon, JavaLand, JSFDays, CON-FESS Vienna and JavaOne. Hazem is an XIBMer, he worked in IBM for ten years. Now, He is working for Nickelodeon New York as a Mobile Architect. He is also an OpenGroup Master Certified Specialist.

One thought on “JavaScript Quiz #1

  1. Pingback: JavaScript Quick Quiz | JavaScript Unit Testing book

Comments are closed.