简体   繁体   English

有没有办法为 JSON.parse reviver 提供上下文?

[英]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.所以我在 JSON 字符串中格式化数据,我需要在 reviver 内部使用我的应用程序上下文(如 this.name 等)。

Code example of reviver: reviver的代码示例:

formatReviver = function (key, value) {

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

}

But obviously THIS does not work inside the Reviver.但显然这在 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.您可以将 reviver 绑定到当前上下文。

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

}).bind(this)

Or use an arrow function, it automatically binds this .或者使用箭头 function,它会自动绑定this

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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