在JavaScript中,' eval '是创建具有动态确定属性的函数的唯一方法吗?
Is `eval` the only way to create functions with dynamically determined arity in JavaScript?
我正在使用JavaScript间谍库,simple-spy .
我发现当监视一个给定的函数时,生成的spy的值始终为0。
这造成了我使用的问题这个套用函数
所以我已经提交了一个pull-request这增加了透明度间谍库。
代码如下:
function spy(fn) {
const inner = (...args) => {
stub.callCount++;
stub.args.push(args);
return fn(...args);
};
// ends up a string like
// 'a,b,c,d'
// depending on the `fn.length`
const stubArgs = Array(fn.length)
.fill(null)
.map((m, i) => String.fromCodePoint(97 + i))
.join();
const stubBody = 'return inner(...arguments);';
// this seems to be the only way
// to create a function with
// programmatically specified arity
const stub = eval(
// the wrapping parens is to
// prevent it from evaluating as
// a function declaration
`(function (${stubArgs}) { ${stubBody} })`
);
stub.reset = () => {
stub.callCount = 0;
stub.args = [];
};
stub.reset();
return stub;
}
exports.spy = spy;
这似乎可以工作。
这是可能的吗不使用eval
?
有可能减少eval
的使用甚至比这个更少?
我知道还有其他问题使用这个间谍实现。这很简单,但很有效对于我目前的用例
就像Benjamin写的那样,我使用了一个简单的:
function spy(fn) {
const stub = (...args) => {
stub.callCount++;
stub.args.push(args);
return fn(...args);
};
stub.reset = () => {
stub.callCount = 0;
stub.args = [];
};
stub.reset();
Object.defineProperty(stub, 'length', {value: fn.length});
return stub;
}
exports.spy = spy;
好看多了
相关文章:
- 如何使对象属性函数成为事件发射器
- 属性函数的 JavaScript 初始值
- 类型错误: 无法设置未定义的属性<函数>
- Javascript set 属性函数不起作用
- 在循环中运行对象属性函数
- 为什么在枚举属性/函数时键长度不准确
- 主干模型获取属性函数返回上次更新的值
- 使用 Jquery 和对象属性函数时出现类型错误
- Javascript:属性函数中的引用
- 导出的目的是什么属性函数在挖空.js库中
- 检查全局属性/函数是否已在 JavaScript 中被覆盖
- 误解了输入文本值属性函数的正确使用
- 将onClick函数绑定到选项卡的href属性函数
- 当函数的属性函数被调用时,是否可以修改函数本身
- 命名对象属性函数
- Javascript -为什么要循环?(原型属性->构造函数属性->函数对象->构造函数属性)
- 如何从属性函数中引用上面的对象
- Javascript继承:子类型原型不能访问超类型的属性/函数
- 破坏性映射对象属性函数
- React.js:如何定义默认属性函数