0

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?

1

6 Answers 6

0

Look at what you are returning from Func1:

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

You return an object, and that object is assigned to func1. So func1 = Func1(); simply calls Func1, and assigns the result of that to func1.

Sign up to request clarification or add additional context in comments.

Comments

0

JavaScript doesn't need the new keyword. The above code assigned the return value to the newly created func1 variable.

Comments

0

Your function is creating an object with:

{
    alert: function() { alert( "Lady Gaga" ); }
};

Using that notation, there's no need to use the new operator.

Comments

0

The () actually executes the function, which returns an object with a method (a method is a property of type function).

In JS, you don't explicitly call new to create new objects:

var song = {
  name: "Entrenched",
  artist: "Morbid Angel"
};

song.artist = "Bolt Thrower";

This creates an object with the properties name and artist.

Comments

0

The new keyword used with a function is one way to create an object, but not the only way. It means that a new object will be created with the specified function called as a constructor - within the constructor the this keyword will reference the new object, and the new object will be returned. Call the same function without the new keyword and an object will not be created.

The object literal syntax (e.g., var x = { }; or return { };) is another way to create an object.

Comments

-1

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

1 Comment

Object literals are not JSON. Also the two examples given are not the same because the resulting objects will have different prototypes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.