do.
do.

Reputation: 617

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?

Upvotes: 0

Views: 76

Answers (6)

Francis
Francis

Reputation: 3383

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

Upvotes: -1

nnnnnn
nnnnnn

Reputation: 150080

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.

Upvotes: 0

helpermethod
helpermethod

Reputation: 62304

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.

Upvotes: 0

Nicolás Ozimica
Nicolás Ozimica

Reputation: 9758

Your function is creating an object with:

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

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

Upvotes: 0

Russell
Russell

Reputation: 17737

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

Upvotes: 0

James Allardice
James Allardice

Reputation: 166061

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.

Upvotes: 0

Related Questions