Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am trying to avoid "const that = this", "const self = this" etc. using es6. However I am struggling with some constructs in combination of vue js and highcharts where you got something like this:

data () {
  let that = this
  return {
    highchartsConfiguration: {
      ... big configuration ...
      formatter: function () {
        return this.point.y + that.unit
      }
    }
  }
}

I'd like to have the that defined just in formatter object if possible. Using arrow syntax () => {} would me allow to use this from data scope, but i would lose the power of giving the function an extra scope.

I do not want to modify the used libraries.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
212 views
Welcome To Ask or Share your Answers For Others

1 Answer

The example illustrates the problem that persists in older libraries like Highcharts and D3 that emerged before current JS OOP practices and strongly rely on dynamic this context to pass data to callback functions. The problem results from the fact that data is not replicated as callback parameters, like it is usually done in vanilla JS event handlers or jQuery callbacks.

It is expected that one of this contexts (either lexical or dynamic) is chosen, and another one is assigned to a variable.

So

const that = this;

is most common and simple way to overcome the problem.

However, it's not practical if lexical this is conventionally used, or if a callback is class method that is bound to class instance as this context. In this case this can be specified by a developer, and callback signature is changed to accept dynamic this context as first argument.

This is achieved with simple wrapper function that should be applied to old-fashioned callbacks:

function contextWrapper(fn) {
    const self = this;

    return function (...args) {
        return fn.call(self, this, ...args);
    }
}

For lexical this:

data () {
  return {
    highchartsConfiguration: {
      formatter: contextWrapper((context) => {
        // `this` is lexical, other class members can be reached
        return context.point.y + this.unit
      })
    }
  }
}

Or for class instance as this:

...

constructor() {
  this.formatterCallback = this.formatterCallback.bind(this);
}

formatterCallback(context) {
    // `this` is class instance, other class members can be reached
    return context.point.y + this.unit
  }
}

data () {
  return {
    highchartsConfiguration: {
      formatter: contextWrapper(this.formatterCallback)
    }
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...