3
function Person()
}

function Person.prototype.init() {   
  request('http://google.fr').on('error', this.onError.bind(this));
}

function Person.prototype.onError(error) {
  console.log(error);
}

bind.this is in init() required. What ECMAScript 6 alternatives do I have here to deal with this? Is this the only solution, doesn't seem that I can apply the arrow here.

Mahoni
  • 7,088
  • 17
  • 58
  • 115

2 Answers2

2

To answer your question directly, ES6 doesn't offer any additional functionality that we can use to avoid binding onError at its point of invocation. ES6 hasn't done away with the behaviour of JavaScript's execution context.

As a side note, the way that you are declaring your instance methods is illegal and will throw an error. They should be declared as follows:

Person.prototype.init = function () {   
    request('http://google.fr').on('error', this.onError.bind(this));
};

Person.prototype.onError = function (error) {
    console.log(error);
};

Currently your onError method will not suffer from any errors if passed unbound. This is because you don't use this inside the onError method's body:

// Safe unbound method
Person.prototype.onError = function (error) {
    console.log(error);
};

// Unsafe unbound method
Person.prototype.onError = function (error) {
    console.log(this, error);
             // ^^^^
};
sdgluck
  • 24,894
  • 8
  • 75
  • 90
1

You can use fat arrow functions:

request('http://google.fr').on('error', (error) => this.onError(error));
Buzinas
  • 11,597
  • 2
  • 36
  • 58