Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 737
balteo Avatar asked Mar 21 '23 06:03

balteo


2 Answers

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);
like image 76
Johanna Larsson Avatar answered Apr 26 '23 03:04

Johanna Larsson


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

like image 27
fiskeben Avatar answered Apr 26 '23 02:04

fiskeben