Javascript "this" variable confusion

Posted by Assaf M on Stack Overflow See other posts from Stack Overflow or by Assaf M
Published on 2010-12-25T21:15:46Z Indexed on 2010/12/25 21:54 UTC
Read the original article Hit count: 304

Filed under:
|
|
|
|

Hi

I am currently reading the book "Javascript: The Good Parts" and was playing with Functions. I produced a test script to test some properties and I am somewhat confused by the results. Here is the code:

<h3>Object</h3>
        <div style="padding-left: 10px;">
            <script type="text/javascript">
                function outterF()
                {
                    document.writeln("outterF.this = " + this + "<br>");

                    function innerF() 
                    {
                        document.writeln("innerF.this = " + this + "<br>");
                        return this;
                    };

                    var inner = innerF();
                    return this;
                }

                document.writeln("<b>From Inside:</b><br>");
                var outF = outterF();
                var inF = outF.inner;

                document.writeln("<br>");
                document.writeln("<b>From Outside:</b><br>");
                document.writeln("outterF.this = " + outF + "<br>");
                document.writeln("innerF.this = " + inF + "<br>");
            </script>
        </div>

Result is:

Object
From Inside:
outterF.this = [object Window]
innerF.this = [object Window]

From Outside:
outterF.this = [object Window]
innerF.this = undefined

Notice that outF.inner returns "undefined", is that some kind of a language bug?
Obviously, outF.inner points to Window object that has nothing to do with my object but shouldn't it be at least pointing to a Function object instead?

Thanks
-Assaf

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about jQuery