我正在浏览一个为 JavaScript 创建多平台包管理和模块系统的代码库。
我找到了一条代码路径,该路径是从与“exports”变量关联的函数中提取的。 我附上了下面的代码片段,在运行该片段时,您会发现“print”对象从函数中提取出来。 我想知道两件事:-
- 这段代码是如何工作的?
- 如果没有 with 语句,能否以更简单的方式实现此代码?
var context = {
exports: {}
};
var fn = (function(args) {
with(args) {
return function logger() {
exports = {
print: function(res) {
console.log(res);
}
}
}
}
});
fn = fn(context);
fn.call();
context.exports.print('hello World'); //Prints the hello world
最佳答案
首先,评估一个非字符串是没有意义的。删除 eval
调用并仅使用该函数。
从技术上讲,with
语句是这样做的:
The
with
statement adds an object environment record for a computed object to the lexical environment of the current execution context. It then executes a statement using this augmented lexical environment. Finally, it restores the original lexical environment.
基本上,这意味着当您将对象分配给标识符 exports
时,它会成为 args
的属性。
不要这样做。 with
语句性能不好,在严格模式下是不允许的。正常赋值即可。
var fn = function(args) {
return function logger() {
args.exports = {
print: function(res) {
console.log(res);
}
}
}
};
关于javascript - 这段代码中发生了什么,以及在没有 "with"关键字的情况下以下代码的基本实现是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34913938/