Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
230 views
in Technique[技术] by (71.8m points)

javascript - ES6 avoid that/self

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

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

1 Reply

0 votes
by (71.8m points)

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)
    }
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...