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)
}
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…