Javascript Scope
<pre><code>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"&gt;

&lt;html xmlns="http://www.w3.org/1999/xhtml"&gt;

&lt;head&gt;
    &lt;title&gt;Youtube embed test&lt;/title&gt;
    &lt;script type="text/javascript" src="swfobject/swfobject.js"&gt;&lt;/script&gt;
    &lt;script type="text/javascript"&gt;
        function onYouTubePlayerReady( playerid )
        {
            ytplayer = document.getElementById("myytplayer");
        }

        function embedPlayer()
        {
            var params = { allowScriptAccess: "always" };
            var atts = { id: "myytplayer" };
            swfobject.embedSWF("http://www.youtube.com/apiplayer?enablejsapi=1",
                       "ytapiplayer", "1024", "768", "8", null, null, params, atts);
        }

        function loadVideo( id, start )
        {
            ytplayer.loadVideoById( id, start );
        }
    &lt;/script&gt;
&lt;/head&gt;

&lt;body onload="embedPlayer()"&gt;
    &lt;div id="ytapiplayer"&gt;
        You need Flash player 8+ and JavaScript enabled to view this video.
    &lt;/div&gt;

    &lt;a href="javascript:void(0);" onclick="loadVideo('bBObeZ6Vj3A',2);"&gt;Load&lt;/a&gt;

&lt;/body&gt;
&lt;/html&gt;
</code></pre>

<p>I'm new to Javascript so I'm having trouble trying to get this to work. The debugger is telling me that ytplayer is undefined in function loadVideo(). Why is this? I understand that the variable declared in onYouTubePlayerReady goes out of scope when the brace ends. So how can I access the loadVideoById method? What confuses me further is that I can do something like this:</p>

<pre><code>&lt;a href="javascript:void(0);" onclick="ytplayer.loadVideoById('e1h5TzdTq0o', 0);"&gt;test&lt;/a&gt;
</code></pre>

<p>and it turns out that, that is perfectly legal. But why am I allowed to use ytplayer? I'm assuming it has something to do with the callback function onYouTubePlayerReady?</p>
