Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>It is as Sean says: you aren't actually creating a new reference to an object (creating a <em>this</em> context), because you are simply calling the constructor - not utilizing the constructor to create a new object. If you use the <strong>new</strong> keyword, it works just peachy.</p> <p>Since the scope of <em>test()</em> is <em>window</em> when you call it, any function called from within <em>test()</em> will execute in the <em>window</em> scope. </p> <p>By using the <strong>new</strong> keyword, you are allocating a new object to memory - and creating a new scope.</p> <p>For example, try this in firebug:</p> <pre><code>var myFunction = function() { this.memberVariable = "foo"; console.log(this); } myFunction(); console.log(window.memberVariable); var myObject = new myFunction(); console.log(myObject.memberVariable); </code></pre> <p>You will see this result:</p> <pre><code>Window stats foo Object { memberVariable="foo"} foo </code></pre> <p>The Function base object has a method, <em>call()</em>, which as outlined by Craig, allows you to explicitly specify which scope the function should run in:</p> <pre><code>var myFunction = function() { this.memberVariable = "foo"; } myFunction.call(myFunction); console.log(myFunction); // "Function()" console.log(myFunction.memberVariable); // "foo" </code></pre> <p>This is, however, not the preferred way of doing things, as you aren't actually creating a new object here, and typeof myFunction will still return "function" instead of "object" - when you really just wanted to create an object.</p>
 

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