1

I have been programming in JS for about a year, and I swear there was a way to do this:

function a(){

}.bind(this);

or

function a(){

}.apply(this,null);

I can do this:

(function a(){
    console.log('b');
}).apply(null);

a(); //but this will throw an error

is there a way to do what I am trying to do? I just want to invoke apply, call or bind on a function without losing scope.

Alexander Mills
  • 90,741
  • 139
  • 482
  • 817
  • Since the introduction of the language it has not been possible to use a function defined in a function declaration statement immediately in the same statement. Other than that, it's not clear what you're asking. What do you mean by "losing scope"? – Pointy Aug 31 '15 at 23:43

1 Answers1

2

Are you looking for

var a = function a() {
  // ...
}.bind(this);

? You can't use a function as an expression in the context of a function declaration statement; the syntax just doesn't allow it. However, you can get an effect very similar to a function declaration statement by instantiating the function in an expression and assigning the reference to a local variable, as above. When you do that, your function is instantiated in the context of an expression, and so using it as an object base to call .bind() works fine.

Pointy
  • 405,095
  • 59
  • 585
  • 614
  • yes this is probably it – Alexander Mills Aug 31 '15 at 23:46
  • it should also work in an object literal, can you provide that syntax also as an example? {a: function(){}.bind(this)} – Alexander Mills Aug 31 '15 at 23:47
  • 1
    @AlexMills it's pretty much the same in an object literal - so long as the `function` keyword isn't the very first token in a *statement*, you're dealing with a function instantiation expression, and you can do the `.bind()` thing or anything else like that. Note that the right-hand side of a property declaration in an object initializer (`foo: function blah() ...`) is not a *statement* - it's part of the object initializer syntax, so the function part is just an expression, not a function declaration statement. – Pointy Aug 31 '15 at 23:49
  • @Pointy To be pedantic, I don't recall hearing the expression "instantiate a function" or "instantiate a function in an expression". I thought it was just "function expression". –  Sep 01 '15 at 03:16
  • @torazaburo I am not a good source for accurate terminology. I personally like "function instantiation expression" because I think it captures what's going on, but I think you're right that the spec just calls it a "function expression". – Pointy Sep 01 '15 at 04:04