Perfection Kills Quiz (part 7)
Previous posts on Perfection Kills JavaScript quiz: 1, 2, 3, 4, 5, 6.
7)
var foo = {
bar: function(){ return this.baz; },
baz: 1
}
typeof (f = foo.bar)();
Correct answer: "undefined".
This question is very similar to the previous one (see part 6).
First, let's consider the following snippet of code, which looks very similar:
var foo = {
bar: function(){ return this.baz; },
baz: 1
}
typeof foo.bar();
This snippet of code returns the value "number". foo.bar points to a function, and when this function is invoked, its this keyword refers to the object foo.
In the original snippet of code, we start by assigning the value of foo.bar to the variable f. As a result, the variable f points to the function function(){ return this.baz; }
. However, when this function is invoked, the keyword this no longer refers to foo. The original snippet of code is roughly equivalent to the following one:
var f = function(){
return this.baz;
}
typeof f();
The function function(){ return this.baz; }
is invoked as a freestanding function, so the keyword this refers to the global object. As the global object does not have the property baz, the function returns undefined. Since typeof undefined
is "undefined", the return value of our snippet of code is "undefined".
All posts on Perfection Kills JavaScript quiz: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14.