Functions

Functions are typically created in JavaScript using the function keyword, using one of the following forms:

function f() {
console.log('function1', this);
}
const g = function(name) {
console.log('function ' + name, this);
}
f(); // calls f
g('test'); // calls g() with a parameter

The this keyword refers to the object that owns the function. If this code runs in a browser, and this is a top-level function created in the <script> block, the owner is the global window object. Any properties accessed via this refer to that object.

A function can be placed in the scope of an object, behaving as a method. The this reference in the following code refers to the obj object and can access this.a and this.b:

const obj = {a: 5, b: 6}
obj.method = function() {
console.log('method', this)
}
object.method()

Arrow functions were introduced in ES2015. They are much more compact and can lead to cleaner code, but the scope of this is no longer retained by the object. In the following code, it refers to the global window object. Code that uses this.a and this.b will not find any data in the object and will return undefined:

obj.arrow = () => console.log('arrow', this)
object.arrow()

You can use arrow functions in Chart.js callbacks, but you should use regular functions instead of arrow functions if you need to access the instance of the chart, usually available using this.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset