Yotam
Yotam

Reputation: 10485

Can't understand a JavaScript function return

I am new to JS and encountered several new thins. For example I saw this piece of code:

function baz() {
    var x = 1;
    return {
        foo: function foo() {return ++x},
        bar: function foo() {return --x},
    };
}

var closures = baz();
alert(closures.foo(),closures.bar());

It is supposed to show a shared variable. My question is - what is being returned?

Is it simply an object with two functions foo() and bar()? Thanks

Yotam

Upvotes: 2

Views: 157

Answers (4)

Denys Séguret
Denys Séguret

Reputation: 382150

Yes, it's "simply an object with two functions foo() and bar()".

But this function is also declared in a closure, which means it can have this private property x which

  • is visible and modifiable by both functions
  • can't be read or modified otherwise

The main differences with

var x = 1;
var closures = {
    foo: function() {return ++x},
    bar: function() {return --x},
};

is that

  • x is protected by the closure creating the object
  • there can be no name conflict regarding x, and the global namespace isn't cluttered

Upvotes: 4

aug
aug

Reputation: 11714

The function baz sets a variable x to be 1 and then creates returns an object. This object has two fields one being foo and the other being bar. A little quick thing about objects is that if you want to access a field you simply need to call object.fieldname. We'll get more into that later.

The functions foo and bar are pretty simply. If you aren't sure what ++x and --x does here is a good Stackoverflow question:

Incrementing in C++ - When to use x++ or ++x?

Basically it is saying it will perform the statement and then increment or decrement x. Because it is returning x I believe it will return 1, and then increment or decrement x.

At the end of the function a variable called closures is defined and this is the object that is returned from the function. Like I said before, in order to access the fields, all you would need to do is do object.fieldname which in this case would be closures.foo() or closures.bar() (the parentheses are necessary to run the function).

I just tested it out and your alert shows 2. I believe the reason is that it doesn't understand the syntax of alert(int,int) so it shows the first alert only.

Upvotes: 0

Quentin
Quentin

Reputation: 943568

The function baz returns an object with two properties (foo and bar). The values of those two properties are functions (both of which modify and return the value of the same x variable).

Upvotes: 3

Mateusz
Mateusz

Reputation: 2317

Yo can even omit the foo() after function, because those properties will be named as you see, and those functions can be anonymous as well so: return { var foo: function() {return ++x}, var bar: function() {return --x}, };

So you have object with properties which are functions.

Upvotes: 1

Related Questions