Search code examples
javascriptsalesforcelwc

Is there a 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

}

Any other ideas?


Solution

  • you can bind the reviver to the current context.

    formatReviver = (function (key, value) {
     if(this.name === value)
     //do stuff
    
    }).bind(this)
    

    Or use an arrow function, it automatically binds this.

    formatReviver = (key, value) => {
     if(this.name === value)
     //do stuff
    }