我有一个 json,函数作为字符串存储在其中,当我使用 new Function 恢复它并尝试使用恰好使用像 lodash 这样的 angular 导入的库的方法时,我得到了一个引用错误。这是 ZombieLoader 将恢复 json 对象的代码,并且在 Angular 类测试中将尝试运行它,我将得到错误 _ not found。
// This class takes a json and produces an object with methods
export class ZombieLoader {
static revive(st: string): object {
const result = {};
const obj = JSON.parse(st);
for (const key of Object.keys(obj)) {
if (key.startsWith('@')) {
result[key.substring(1)] = new Function('return ' + obj[key])();
continue;
}
result[key] = obj[key];
}
return result;
}
}
// the json with function in string form that will be hydrated back for use
{
script: '{"@run":"function () { return _.chunk(['a', 'b', 'c', 'd'], 2); };}'
}
// here I test the method which fails because it cant find _
import * as _ from 'lodash';
import {ZombieLoader} from './zombie-loader';
export class Test {
constructor(script: string) {
const sceneScript = ZombieLoader.revive(script);
sceneScript.run();
}
}
为什么重建的对象没有引用 Angular 加载的脚本有没有办法重建对象并将其绑定(bind)到一个 Angular 。 如果我将 lodash 添加到 index.html 文件中,它可以工作,但我不想对其他几个库执行此操作
最佳答案
通过在末尾添加 ()
- new Function('return ' + obj[key])()
你执行函数并且它不知道其调用者中的任何依赖项。
我不知道 run()
在这里 sceneScript.run();
做了什么,但是 Function
构造函数接受 arguments 参数,所以你可以只需传入所需的依赖项:new Function('_', 'return ' + obj[key]);
并稍后通过从调用者传递它来调用函数:
sceneScript.run(_);
关于javascript - Angular 中的新函数构造函数如何在恢复的对象中引用导入的脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56310778/