Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p><strong>Answer 1:</strong></p> <p>You added the 'Log' function to the 'this'. That's the reason you have to create object from Console function before you can access it.</p> <p>When you do Console().Log(), you are trying to run Console function and call 'Log' method on the returned object. Because Console function doesn't return anything, it is 'undefined' and hence you can't access the Log method. </p> <p><strong>Answer 2:</strong></p> <p>The 'logger' is not a function but result of the anonymous function output.</p> <pre><code>E.g. var logger = function() { //your code; } (); </code></pre> <p>Your anonymous function doesn't return anything so logger will be 'undefined'. And for an undefined object, there is no 'log' method.</p> <p>To solve this problem, do this:</p> <pre><code>var logger = function() { var output = {}; output.log = function(msg) { new Console().Log(msg); new Console().Log("log initialized"); } output.log2 = function(msg) { new Console().Log(msg); new Console().Log("log2 initialized"); } return output; }(); To use, you can write, logger.log('hello'); </code></pre> <h2>Understanding function and Object creation in JS</h2> <p>The main thing you have to understand is that in JavaScript, a regular function acts as a 'constructor' when called with 'new' keyword.</p> <p>Consider following function. </p> <pre><code>function Console() { this['name'] = 'Console' } </code></pre> <p>When you call above function like this,</p> <pre><code> Console(); alert(window.name); //alerts 'Console'; </code></pre> <p>'this' will be the 'window' object and it will add 'name' property with the value of 'Console'.</p> <p>If you call the above function like,</p> <pre><code> var output = new Console(); alert(output.name) // alerts 'Console' </code></pre> <p>JavaScript will create a new object which is accessible using 'this' inside 'Console'. Now output will have 'name' property. </p> <p>Let me know if above doesn't clear up things for you. It's essential that you understand it to be able to take advantage of what JS has to offer.</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