Search code examples
javascriptnew-operator

object issues of javascript


I constructed a function defined as

var Func1 = function() 
{
    return {
             alert: function() { alert( "Lady Gaga" ); }
           };
};

And I assigned Func1() to a variable, like this:

var func1 = Func1();

I found something make no sense to me that Func1() created an object for func1 although I didn't put the new in front of it.

Isn't that objects could only be created by new?

What happened when the expression above is being executed?


Solution

  • When you write a javascript literal object (json like), it's the equivalent to create a new object with the new operator and assign its properties.

    This

    var a = { test: 123, caca: 'pipi' };
    

    Is the same as

    var a = new Object();
    
    a.test = 123;
    a.caca = 'pipi';