JavaScript Corners – Part 8
References (Continued)

JavaScript Corners – Part 8
References (Continued)

Given an object o  with a member function f  that prints out what the this value is:

We know what the following prints:

And we know what the following prints1:

I always thought that the difference came down to the fact that o.f()  is actually invoking a different operator — something like a “member call operator”.

However, what do you think the following prints?

My guess, up until today, would have been that this prints “global”, since with the parentheses, this is no longer invoking the member call operator, but is instead invoking the call operator.

But I was wrong. There is no such thing as a “member call operator”. Rather, the “call” operator just behaves differently depending on whether the target of the call is a value or a reference2.

So this actually prints “o”.

But hang on. Why didn’t the parentheses coerce o.f to a value?

One might have expected the parentheses to automatically dereference  o.f, something like the following examples that use the logical OR and comma operators to coerce the target to a value instead of a reference:

Indeed, this could have been the case for bare parentheses as well, but the language designers chose not to do it that way, so that the  delete and  typeof operators still work when extraneous parentheses are provided:

 


  1. assuming the use strict directive isn’t provided in this case 

  2. To be more accurate, the target also behaves differently depending on whether the target reference refers to a property of an object vs a variable in an environment record 

One Reply to “JavaScript Corners – Part 8
References (Continued)

Leave a Reply