JavaScript Quiz #1

March 14, 2013 in JavaScript

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!

One comment on “JavaScript Quiz #1

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

Leave a reply

Your email address will not be published. Required fields are marked *

320,596 Spam Comments Blocked so far by Spam Free Wordpress

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Powered by sweet Captcha