Note that there are some explanatory texts on larger screens.

plurals
  1. POJavascript factory pattern variable scoping
    primarykey
    data
    text
    <p>I am following a tutorial that is showing the factory pattern to create objects in javascript. The following code has me stumped as to why it works.</p> <pre><code>&lt;html xmlns="http://www.w3.org/1999/xhtml"&gt; &lt;head&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=utf-8" /&gt; &lt;title&gt;6-2.htm&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;script type="text/javascript"&gt; function createAddress(street, city, state, zip) { var obj = new Object(); obj.street = street; obj.city = city; obj.state = state; obj.zip = zip; obj.showLabel = function() { //alert(this.street + "\n" + this.city + ", " + this.state + " " + this.zip); //var obj; alert(obj.street + "\n" + obj.city + ", " + obj.state + " " + obj.zip); }; return obj; }; var JohnAddr = createAddress("12 A St.", "Johnson City", "TN", 37614); var JoeAddr = createAddress("10061 Bristol Park", "Pensacola", "FL", 32503); JohnAddr.showLabel(); JoeAddr.showLabel(); &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>the first commented line seems proper to me (using the <code>this</code> keyword in the showLabel function). i'm not sure how using obj in its place is working. obj would have to reference a global variable somewhere because within that function when its run there is no obj defined, right? since i make 2 objects, its not just luck in this case that both get displayed fine, the older values for obj's contents are stored and referenced properly. but how? if i uncomment the second comment then it breaks and i understand why, now im explicitly telling js that i'm talking about a local variable and there is none.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload