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 ?

4
  • 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. Commented Apr 9, 2015 at 0:20
  • Do you know why is not allowed on declaration ? Commented Apr 9, 2015 at 0: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 ecma-international.org/ecma-262/5.1/#sec-13 Commented Apr 9, 2015 at 0:34
  • Thanks, this is one more reason for throwing away function declaration and always using expression form. I can use methods directly, no hoisting... Commented Apr 9, 2015 at 0:39

1 Answer 1

5

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})();
Sign up to request clarification or add additional context in comments.

1 Comment

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||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.