[英]Is there a way to give context to a JSON.parse reviver?
所以我在 JSON 字符串中格式化數據,我需要在 reviver 內部使用我的應用程序上下文(如 this.name 等)。
reviver的代碼示例:
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)
或者使用箭頭 function,它會自動綁定this
。
formatReviver = (key, value) => {
if(this.name === value)
//do stuff
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.