view core-javascript/global.rst @ 213:0ea90a1819c2 default tip

Custom theming
author Radomir Dopieralski <radomir.dopieralski@allegro.pl>
date Wed, 27 Jun 2012 16:35:54 +0200
parents 29c7fe19aeb5
children
line wrap: on
line source

The global object
=================

JavaScript has a global object.  It is, so to speak, the object of
last resort.  If there's no other suitable object then JavaScript will
use the global object (rather than reporting an error).

.. note::

   Douglas Crockford writes **JavaScript's global object [...] is far and
   away the worst part of JavaScript's many bad parts.**


Getting global
---------------

Here's how to get the global object.

.. code-block:: javascript

   js> return_this = function(){return this;}

   function () {
       return this;
   }

   js> global = return_this()
   [object global]

The programmer who wants to can always obtain access to the global
object.


Global variables
----------------

Global variables are nothing more than attributes of the global
object.

.. code-block:: javascript

   js> s = 'Hello world.'
   Hello world.
   js> global.s
   Hello world.
   js> global.i = 42
   42
   js> i
   42


Global pollution
----------------

It's very easy to inadvertently pollute (change) the global object.
All it takes is an assignment to an undeclared variable in a function.

.. code-block:: javascript

   js> pollute = function(n){ i = n; };
   function (n) {
       i = n;
   }
   js> i
   42
   js> pollute(13)
   js> i
   13

More global pollution
---------------------

There's a more subtle way to pollute the global object, which involves :doc:`JavaScript's this object <what-is-this>`.

To begin with, note that we can push values onto an array.

.. code-block:: javascript

   js> array = []

   js> array.push(1, 2, 3)
   3
   js> array
   1,2,3

Let's try using ``array.push`` as a stand-alone function.

.. code-block:: javascript

   js> p = array.push
   function push() { [native code for Array.push, arity=1] }

   js> p(4, 5, 6)
   3

The push function returns the length of the object it has just pushed
to.  So the value *3* above is a signal that all is not well.  And
indeed it is not.  The original array is unchanged, and the global
object has an entry at *0*.

.. code-block:: javascript

   js> array
   1,2,3
   js>
   js> global[0]
   4

It's also got a length!

.. code-block:: javascript

   js> global.length
   3


Explanation
-----------

This behaviour is a consequence of :doc:`what-is-this` and
:doc:`bind-is-transient`, together with JavaScript's no-exceptions
design.