简体   繁体   中英

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?

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM