Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<ol> <li><p>The <code>new</code> keyword creates an instance of your <code>Console</code> object which you can then call the <code>Log</code> method on. If you just call <code>Console()</code> directly, you'll get whatever the return value is for that function. In your case there is none, so <b><code>undefined</code></b>. Additionally, if you don't use the <code>new</code> keyword, anything you assign to <code>this</code> within that "class function" will pollute the global scope. So instead of assigning your methods to <code>this</code>, you'd have to use a <b>proxy object</b> which you would return instead.</p></li> <li><p>In your example you're assigning the <code>logger</code> variable to the <b>return value</b> of calling your anonymous function. Again, it doesn't return anything so calling <code>new logger()</code> won't work because you can't instantiate <code>undefined</code>. So, removing the trailing <code>()</code> from the anonymous function will assign the <b>function</b> to <code>logger</code> rather than its return value, which you can then instantiate with <code>new</code>. (You could also use a proxy object again).</p></li> </ol> <p>In both the above examples, I'd strongly advise using the <b><code>new</code> keyword</b> rather than creating and returning a proxy object. This takes advantage of Javascript's built in instantiation mechanism and the function prototype chain, and is <b>much faster</b> than object creation.</p> <p>This blog post by John Resig is worth a read for more information on how "class" instantiation works in Javascript: <a href="http://ejohn.org/blog/simple-class-instantiation/" rel="nofollow noreferrer">http://ejohn.org/blog/simple-class-instantiation/</a></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