我想确认我所看到的有关 this 引用的行为,以及使用 reviver 函数修改对象中的键(而不仅仅是值)的能力。
如果我使用 function(key,value {...} 传递我的 reviver 函数,而不是使用箭头函数 (key, value) => {...},此引用似乎指的是正在恢复的对象。这对于 JSON 中的子对象也是如此。我在服务器上的 Node.js 8.x 以及当前的 Chrome 中看到了这一点客户端。
可以理解的是,如果我将函数作为箭头函数传递,则调用上下文将被保留。
我在解析 JSON 时依靠它来添加和删除一些键。
我可以依赖这种行为吗?
var aTestStr = '{"prop1": "this is prop 1",'
+'"prop2": {"prop2A": 25, "prop2B": 13, "prop2C": "This is 2-c"}'
+'}';
var aTestObj = JSON.parse(aTestStr, function(key, value) {
//at this point, this refers to the object being revived
//E.g., when key == 'prop1', this is an object with prop1 and prop2
//when key == prop2B, this is an object with prop2A, prop2B and prop2C
//So is this code reliable?
if (key == this.prop2B) {
//Do something, add a prop to this:
this.prop2BDif = 100 - this.prop2B;
}
});
最佳答案
是的,已记录:JSON.parse documentation in the MDN
If a reviver is specified, the value computed by parsing is transformed before being returned. Specifically, the computed value and all its properties (beginning with the most nested properties and proceeding to the original value itself) are individually run through the reviver. Then it is called, with the object containing the property being processed as this, and with the property name as a string, and the property value as arguments.
关于javascript - JSON.parse Reviver函数: Access to object being revived?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55688816/