On Fri, Feb 4, 2011 at 6:44 PM, mcot <[email protected]> wrote:
> I am currently seeing some weird behavior with the global object:
>
> console.log(window.foo); // this returns undefined
> console.log(this.foo); // this returns undefined
> console.log(foo); // this is a reference error
>
> The Mozilla docs on Reference error simply state:
>
> A ReferenceError is thrown when trying to dereference a variable that
> has not been declared.
>
> I realize accessing a non existent property on an object should return
> undefined... which accounts for the first two cases... but whats going
> on in the third case?
>
In the third case, you're trying to resolve a so-called undeclared
identifier.
When `console.log(foo)` is evaluated, first, `foo` identifier needs to be
resolved against the current scope chain. Once it's resolved, its value can
then be passed to `console.log`. When resolving `foo`, ES3-based
implementations follow behavior described in 10.1.4 — Scope Chain and
Identifier Resolution. If you look at 10.1.4, you'll see that during this
resolution, all objects in the scope chain are being searched for a property
corresponding to an identifier in question — "foo" in this case. Since the
only object in the current scope chain are the global object (considering
that you're executing that statement from within the global code), the
Global Object is the only object that's being searched for "foo". "foo"
doesn't exist there of course, and there are no more objects in the scope
chain, which brings us — via step 1 ("Get the next object in the scope
chain. If there isn't one, go to step 5") — to step 5. Based on that step,
`foo` is supposed to return a reference with base object `null` and property
name "foo". We're almost there. The returned reference now goes through
internal `GetValue` method (during that `console.log(...)` function call),
which is defined to throw a ReferenceError when passed an object with `null`
base. So there you have it — why resolving `foo` (or rather —
`console.log(foo)`) throws ReferenceError.
[...]
--
kangax
--
To view archived discussions from the original JSMentors Mailman list:
http://www.mail-archive.com/[email protected]/
To search via a non-Google archive, visit here:
http://www.mail-archive.com/[email protected]/
To unsubscribe from this group, send email to
[email protected]