A few questions regarding JavaScript's Constructor and Anonymous functions

I have the following JavaScript function:

function Console() {
    this.Log = function(msg) {
        if (document.getElementById("console")) {
            var console = document.getElementById("console");
            console.innerHTML += msg + "<br/>";
        }
    }
}

      

Question 1: Why do I need to use a new keyword?

new Console().Log("hello world");

      

Why can't I do this?

Console().Log("hello world without using new");

      

Question 2:

var logger = function() {
    this.log = function(msg) {
        new Console().Log(msg);
        new Console().Log("log initialized");
    }

    this.log2 = function(msg) {
        new Console().Log(msg);
        new Console().Log("log2 initialized");
    }
}(); //notice the brackets

      

It won't work because of the () at the end of the logger.

new logger().log("hello world");

      

I know that with trailing () it means the function is called immediately, but why isn't it working? This is because the function () {} (); cannot be assigned to other variables?

+2


source to share


3 answers


  • The keyword new

    creates an instance of your object Console

    , which can then be called by the method Log

    . If you just call Console()

    directly, you get the entire return value for that function. In your case, they are not, therefore . Also, if you don't use the keyword , anything you assign inside this "class function" will pollute the global scope. So instead of assigning your methods, you would have to use the proxy object that you would return instead. undefined

    new

    this

    this

  • In your example, you are assigning a variable to the logger

    return valueto call an anonymous function. Again, it doesn't return anything, so the call new logger()

    won't work because you can't create an instance undefined

    . So removing the final ()

    from the anonymous function assigns the function logger

    rather than its return value, which you can then create with new

    . (You can also use the proxy object again).

In both of the examples above, I highly recommend using the keyword rather than creating and returning a proxy object. This uses Javascript built into the function instantiation engine and prototype chain, and is much faster than object creation. new



This blog post by John Resig deserves to read more information on how a class is instantiated in Javascript: http://ejohn.org/blog/simple-class-instantiation/

+5


source


When you execute function(){}()

, you define and call the function as soon as you specified. So when you have this:

var logger = function(){}();

      

You are assigning logger

as the return value of this function, not the function itself. In your example, the function returns nothing, so it logger

will be undefined.



Just as a matter of style when writing anonymous functions that are called immediately, it's pretty standard to wrap the function in parentheses:

var logger = (function() { ... })();

      

This is just a visual hint of what you are going to call this function and it can save a lot of confusion. This is actually very important in some situations: see the comments below!

+2


source


Answer 1:

You have added the "Journal" function to 'this'. This is the reason why you need to create an object from the console before you can access it.

When you execute Console (). Log (), you are trying to run a console function and call the Log method on the returned object. Since the console function returns nothing, it is "undefined" and therefore you cannot access the log method.

Answer 2:

The "registrar" is not a function, but the result of an anonymous function.

E.g. var logger = function() { //your code; } ();

      

Your anonymous function returns nothing, so the log will be "undefined". And there is no "log" method for undefined object.

To fix this problem, do the following:

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');

      

Understanding function and object creation in JS

The main thing you need to understand is that in JavaScript, a regular function acts like a "constructor" when called with the "new" keyword.

Consider the following function.

function Console()
{
    this['name'] = 'Console'
}

      

When you call the function above,

   Console();
   alert(window.name); //alerts 'Console';

      

'this' will be the "window" object and it will add the "name" property with the value "Console".

If you call the above function like

   var output = new Console();
   alert(output.name)  // alerts 'Console'

      

JavaScript will create a new object accessible via 'this' inside the "Console". The output will now have a "name" property.

Let me know if the above does not clarify for you. It is very important that you understand this in order to be able to take advantage of what JS has to offer.

+2


source







All Articles