Context of method (this)

Before getting started with our next sections, the readers may have noticed that we have not used a fat arrow function as a replacement for the callbacks in all cases. This is because we will be using the context of a function (this) widely. There is a difference in implementation between flat arrow functions and regular functions when it comes to context. The differential statement is that the context of function (this) doesn't depend on where it is declared, but from where it is called. To understand this, let's consider the following example:

function getData() {
console.log(this.a); // global
}
getData.a = 'hello';
var a = 'world';
getData();

On running the preceding snippet, we will get the output 'world'; this is because the foo function is called in a global scope, hence the context is global and we receive the value of the global variable. To restrict this behavior, we can use the bind method or es6 arrow functions.
Now, we convert the preceding get virtual method as follows:

Account.virtual('fullname') 
.get(()=>{
return this.firstname + ' ' + this.lastname;
})
The context inside the preceding arrow function won't refer to the Account schema, and will thus get undefined. To avoid this behavior, we will continue with regular functions. Get to know more about the lexical scoping mechanism of the arrow function in the following link: https://goo.gl/bXvFRM. More details on how to handle this issue with different methods are posted in the following link: https://github.com/Automattic/mongoose/issues/5057.
..................Content has been hidden....................

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