如果要动态使用全局函数和变量,可以使用:
window[functionName](window[varName]);
Run Code Online (Sandbox Code Playgroud)
是否可以对本地范围内的变量执行相同的操作?
这段代码工作正常,但目前使用eval,我正在考虑如何做到这一点.
var test = function(){
//this = window
var a, b, c; //private variables
var prop = function(name, def){
//this = window
eval(name+ ' = ' + (def.toSource() || undefined) + ';');
return function(value){
//this = test object
if ( !value) {
return eval('(' + name + ')');
}
eval(name + ' = value;')
return this;
};
};
return {
a:prop('a', 1),
b:prop('b', 2),
c:prop('c', 3),
d:function(){
//to show that they are accessible via to methods
return …
Run Code Online (Sandbox Code Playgroud) 我将如何将轻量级JavaScript写入javascript解析器.简单的东西,可以转换一些代码片段.
我想基本上在函数public中创建内部范围对象.
所以这样的事情
var outer = 42;
window.addEventListener('load', function() {
var inner = 42;
function magic() {
var in_magic = inner + outer;
console.log(in_magic);
}
magic();
}, false);
Run Code Online (Sandbox Code Playgroud)
会编译到
__Scope__.set('outer', 42);
__Scope__.set('console', console);
window.addEventListener('load', constructScopeWrapper(__Scope__, function(__Scope__) {
__Scope__.set('inner', 42);
__Scope__.set('magic',constructScopeWrapper(__Scope__, function _magic(__Scope__) {
__Scope__.set('in_magic', __Scope__.get('inner') + __Scope__.get('outer'));
__Scope__.get('console').log(__Scope__.get('in_magic'));
}));
__Scope__.get('magic')();
}), false);
Run Code Online (Sandbox Code Playgroud)
这背后的动机是序列化功能和闭包的状态,并使它们在不同的机器(客户端,服务器,多个服务器)之间保持同步.为此,我需要一个代表[[Scope]]
问题: