javascriptecmascript-6dom-eventsevent-binding

Bind named function to context


I have a named function like this

function handler(arg) {
  this.arg = arg;
}

Is there a way to bind context to this function?

I'm looking for something like this

function handler(arg) {
  this.arg = arg;
}.bind(this);

that will allow to call this function in any context, but it will always use bound context.

For example I have another function (in vendor code, that I can't edit):

addEventListener(callback) {
   callback(currentArg);
}

where I will pass handler and it will be executed with bound context.


Solution

  • I'm not sure where and how you are going to use it but you can use a function expression instead of function deceleration:

     var handler = function handler(arg) {
      this.arg = arg;
    }.bind(this)
    

    Or just use an arrow function which will use a lexical context for this:

    var handler = (arg) => {...}