Jul 2, 2007

Context

The way context works is through the this variable. The this variable will always refer to the objet that the code is currently inside of. Remember that global objects will actually properties of the window object. This means that even in a global context, the this variable will still refer to an object. Context can be a powerful tool and is an essential one for object-oriented code.

            var obj = {
            yes: function(){
            // this == obj
            this.val = true;
            },

            no: function(){
            this.val = false;
            }
            };

            // We see that there is no val property in the 'obj' object
            alert( obj.val == null );
            // We run the yes function and it changes the val property
            // associated with the 'obj' object
            obj.yes();
            alert( obj.val == true );


            // However, we now point window.no to the obj.no method and run it
            window.no = obj.no;
            window.no();
            // This results in the obj object staying the same (as the context was
            // switched to the window object)
            alert( obj.val == true );
            // and window val property getting updated.
            alert( window.val == false );

            

Javascript also provides a couple of methods to change context. The following example shows these methods.

            // A simple function that sets the color style of its context
            function changeColor( color ) {
            this.style.color = color;
            }
            // Calling it on the window object, which fails, since it doesn't
            // have a style object
            changeColor( "white" );

            // Find the element with an ID of main
            var main = document.getElementById("main");
            // Set its color to black, using the call method
            // The call method sets the context with the first argument
            // and passes all the other arguments as arguments to the function
            changeColor.call( main, "black" );

            // A function that sets the color on the body element
            function setBodyColor() {
            // The apply method sets the context to the body element
            // with the first argument, the second argument is an array
            // of arguments that gets passed to the function
            changeColor.apply( document.body, arguments );
            }

            // Set the background color of the body to black
            setBodyColor( "black" );


            var name = "window";
            var f = (function() { alert(this.name); });
            f(); //window
            f.name = "local";
            f();     //still window, the function still run in the context of window
            f.call(f); //local

            var p = { name: "local" };
            p.f = f;
            p.f(); //local
            f.call(p); //local