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

问题描述

因此,我正在JSON字符串中格式化数据,并且需要在恢复器内部使用我的应用程序上下文(例如this.name等)。

齐磊的代码示例:

formatReviver = function (key,value) {

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

}

但是很明显,这在Reviver内部不起作用。

我的想法是在参数内使用认值:

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

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

}

还有其他想法吗?

解决方法

您可以将Reviver绑定到当前上下文。

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

}).bind(this)

或者使用箭头功能,它会自动绑定this

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