Arrow functions

Another notable change to the language was the addition of arrow functions. With this, we have now gotten access to change this without having to resort to various hacks on the language. An example of this can be seen as follows:

const create = function() {
this.x = 10;
console.log('this', this);
const innerFun = function() {
console.log('inner this', this);
}
const innerArrowFun = () => {
console.log('inner arrow this', this);
}
innerFun();
innerArrowFun();
}
const item = new create();

We are creating a constructor function for a new object. We have two inner functions, one being a basic function call and the other being an arrow function. When we print this out, we notice that the basic function prints the window's scope. When we print the inner arrow function's scope, we get the scope of our parent.

We could solve this in a few ways for the basic inner function. First, we could declare a variable in the parent and utilize that for the inner function. Also, when we run the function, we could use call or apply to actually run the function.

However, neither of these is a good idea, especially when we now have arrow functions. A key point to remember is that the arrow function takes the scope of the parent, so whatever this points to for the parent, we are now going to do the same inside the arrow function. Now, we can always change that by utilizing apply on an arrow function, but it is best to only utilize apply and such for partial application reasons and not to call functions by changing its this keyword.

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

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