balteo
balteo

Reputation: 24679

Odd syntax: invoking a javascript function with two parenthesis pairs

I am currently reading a book about AngularJS and I have a question regarding a javascript syntax that I don't understand.

var element = $compile('<button></button>')($rootScope);

How come the one can invoke a function with a two parenthesis pairs?

  1. ('<button></button>')
  2. ($rootScope)

Can anyone please advise about this js construct?

Upvotes: 4

Views: 105

Answers (3)

Johanna Larsson
Johanna Larsson

Reputation: 10761

It is no special construct, it is simply a function that returns a function.

function a () {
    return function () {
        console.log("hello");
    };
}

a()();

AngularJS $compile takes some HTML string and returns a template function which in turn can be called.

Your snippet of code, written over two lines, would look like this:

var template = $compile('<button></button>');
var element = template($rootScope);

Upvotes: 4

Quentin
Quentin

Reputation: 943935

$compile('<button></button>') calls a function. It returns something. ($rootScope) is applied to the return value (which is presumably another function).

For a simple example:

function one() {
    return two;
}

function two() {
    alert("Hello");
}

one()();

Upvotes: 1

fiskeben
fiskeben

Reputation: 3467

$compile('<button></button>') returns a function that is immediately executed by the second set of parenthesis.

Upvotes: 2

Related Questions