В Javascript
, если я попытаюсь сделать это:
var obj = {};
obj.z.c.f.d = 'foo';
'TypeError: Cannot read property 'c' of undefined'
at repl:1:7
at ContextifyScript.Script.runInThisContext (vm.js:50:33)
at REPLServer.defaultEval (repl.js:240:29)
at bound (domain.js:301:14)
at REPLServer.runBound [as eval] (domain.js:314:12)
at REPLServer.onLine (repl.js:442:10)
at emitOne (events.js:121:20)
at REPLServer.emit (events.js:211:7)
at REPLServer.Interface._onLine (readline.js:282:10)
at REPLServer.Interface._line (readline.js:631:8)
Я не хочу, чтобы эта ошибка была выбрана.
Просто создайте zcf
и добавьте d
значение внутри.
У нас есть устаревший код.
Теперь я хочу обернуть это obj в прокси и уловить его методы.
Если свойство undefined, создайте там один объект, если значение не объекта; перезапишите его.
Я реализовал этот метод, и я просто могу использовать этот метод в ловушке прокси, возможно:
// setByString is not in Object.prototype. Only in my testObject
testObject.setByString('f.o.o', 1999);
// this adds an f object and an o object inside, then an o value with 1999 to testObject. Merges deeply.
Здесь ожидается, что в моем testObject
будут только номера, неопределенные, строки, объекты.
Дело в том, что я не могу сделать это с помощью прокси.
Кажется, у них нет того, что мне нужно.
Во всяком случае, есть ли способ сделать это, если это невозможно с помощью Proxies?
с прокси-серверами вы можете делать именно то, что вы ищете:
var handler = {
get: function(target, name){
if(!(name in target))
target[name] = new Proxy({}, handler);;
return target[name];
}
};
var p = new Proxy({}, handler);
Теперь попробуйте:
p.a.b.c = 45;//no TypeError here !!!
Это то, чего вы ожидали?
Попробуй это
var testObject = {};
setByString(testObject, 'f.o.o', 1999);
console.log(testObject);
function setByString(obj, props, val) {
var current = obj;
props.split('.').forEach((prop, index, self) => {
current[prop] = index !== self.length - 1 ? current[prop] || {} : val;
current = current[prop];
});
}
util.inspect(p, { depth: null, colors: true })
, я получаю:RangeError: Maximum call stack size exceeded at formatValue (util.js:423:37) at formatProperty (util.js:833:11) at formatValue (util.js:612:17) at formatProperty (util.js:833:11) at formatValue (util.js:612:17) at formatProperty (util.js:833:11) at formatValue (util.js:612:17) at formatProperty (util.js:833:11) at formatValue (util.js:612:17) at formatProperty (util.js:833:11)
console.log(JSON.parse(JSON.stringify(p)));
выдает ту же ошибку стека вызовов.