Way to give context to a JSON.parse reviver?

So I am formatting data inside JSON Strings and I need to use my application context (like this.name etc.) INSIDE the reviver.

Code example of reviver:

formatReviver = function (key, value) {

 if(context.name === value)
 //do stuff

}

But obviously THIS does not work inside the Reviver.
An idea I had is to use default values inside the parameter:

formatReviver = function (key, value, context = window) {

 if(context.name === value)
 //do stuff

}

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

Use an arrow function instead:

formatReviver = (key, value, context = window) => {

  if(context.name === value)
  //do stuff

}

This syntax preserves "this" (context) as opposed to the function keyword, which changes the this scope depending on how it’s used.

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply