我正在探索我正在开发的 JavaScript 路由框架的各种选项,并且我想提供一个用 JavaScript 编写的 DSL 来定义路由器。
我的想法是在 String 类上使用临时原型(prototype)覆盖(维护先前原型(prototype)值的哈希值,覆盖,运行 DSL 代码,将原型(prototype)值重置为原来的值),以实现如下所示:
DSL.run(function() {
"hello".isSomething();
"foo".isSomethingElse();
});
另一个想法是使用定义临时全局变量,然后在 DSL 运行完成后删除/重置它们。这样,如果您使用 window
(或任何全局对象)作为 this
上下文运行 DSL 闭包,我相信您应该能够执行以下操作:
DSL.run(function() {
defineSomething("hello");
defineSomethingElse("foo");
});
我知道我知道我知道我应该非常小心原型(prototype)重载和污染全局命名空间,但这似乎是一种非常本地化且易于清理的方法,可以防止此类事情发生。我的问题是,还有其他考虑因素会阻止这成为现实吗?
我能想到的一个潜在问题是这是否适用于 Node.js 设置,其中代码存储在单独的模块中并且全局变量彼此保持独立,我认为这会消除选项 B,但是 String 原型(prototype)重载呢?这些是在模块之间共享的,对吧?例如如果我包含模块 A,它设置 String 原型(prototype)值,那么这些原型(prototype)值将在包含代码中可用,对吗?
另外,请告诉我是否有人以前做过此类事情。我认为这是解决此类问题的一种聪明方法,而且我还没有见过类似的方法,但我想确保我不会遗漏一些非常明显和可恶的东西。
最佳答案
使用删除 String.prototype[method]
。
var dsl = function(f){
var _ = String.prototype;
_.isSomething = function(){
console.log('isSomething: '+this);
}
_.isSomethingElse = function(){
console.log('isSomethingElse: '+this);
}
f();
delete _.isSomething;
delete _.isSomethingElse;
}
dsl(function(){
"hello".isSomething(); // isSomething: hello
"foo".isSomethingElse(); // isSomethingElse: foo
});
// "hello".isSomething(); // error "Object has no method 'isSomething'"
// "foo".isSomethingElse(); // error "Object has no method 'isSomethingElse'"
关于javascript - 临时全局变量/函数和原型(prototype)重写来编写 JS DSL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13150164/