0

I'm reading a piece of code that is built like this:

var Template = function() { return `<?xml version="1.0" encoding="UTF-8" ?>
  <document>
  //other stuff
  </document>`
}

The function is used in another file by doing

var resource = Template.call(self);

Coming from a C++/Objective-C/Swift background, I am guessing it's a function named Template and returns whatever the stuff inside is. Could someone advise me what this construct is supposed to be?

Kelvin Lau
  • 5,773
  • 3
  • 28
  • 49
  • 2
    Yes, that's a function expression. The thing inside of it is an ES6 template string (doing string interpolation). – Bergi Sep 13 '15 at 20:35
  • 1
    This thread might help you - [var functionName = function() {} vs function functionName() {}](http://stackoverflow.com/questions/336859/var-functionname-function-vs-function-functionname) – Ori Drori Sep 13 '15 at 20:48

1 Answers1

3

Within the body of a script,

var x = function() { };

is equivalent to

function x() { }

as the first is a variable declaration with a function body assigned, it should be terminated by a ; other than a function definition.

The reason doing something like this is, that the variable scope applies. Having this inside a function

function a() {


      var x = function () { ... };

}

means, that function x isn't defined outside of a; calling x outside of a results in a reference error.

Axel Amthor
  • 10,616
  • 1
  • 20
  • 42