8

Why is this allowed ?

var f = function() {
  console.log(this.x);
}.bind({x:1})();

And why this is not or better why I get syntax error in this case ?

function f() {
  console.log(this.x);
}.bind({x:1})();

So, why I need function expression syntax to get this work and is there a way to use bind method directly on function declaration ?

user3448600
  • 3,648
  • 5
  • 17
  • 23
  • 1
    A function declaration is not an expression, so you can't do that. But you can force an expression `!function f(){}.bind({x:1})()`. Look for info on [IIFE](http://stackoverflow.com/questions/8228281/what-is-the-function-construct-in-javascript). – elclanrs Apr 09 '15 at 00:20
  • Do you know why is not allowed on declaration ? – user3448600 Apr 09 '15 at 00:28
  • 1
    Because it is not an expression. The syntax is ambiguous, you have to disambiguate by forcing an expression. Check the spec for more info http://www.ecma-international.org/ecma-262/5.1/#sec-13 – elclanrs Apr 09 '15 at 00:34
  • Thanks, this is one more reason for throwing away function declaration and always using expression form. I can use methods directly, no hoisting... – user3448600 Apr 09 '15 at 00:39

1 Answers1

4

The second example works but the syntax is slightly off:

Surround the function in parens. I have to say that I'm not entirely sure why. It seems like it would work without the parens huh? :P

(function f() {
    console.log(this.x);
}).bind({x:1})();
Halcyon
  • 57,230
  • 10
  • 89
  • 128
  • 3
    parens make an expression, and thus an anon function, and thus a "tail value". you can also do the prefix-only alternative to paren wraps: `0||` – dandavis Apr 09 '15 at 01:15