Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using function.prototype.bind directly on function declaration

Tags:

javascript

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 ?

like image 237
user3448600 Avatar asked Apr 09 '15 00:04

user3448600


1 Answers

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})();
like image 186
Halcyon Avatar answered Oct 17 '22 04:10

Halcyon