通过名称调用函数
有时我们需要通过函数名来调用函数。我可以用纯 JavaScript 执行此操作,如下所示:
global=this
function add(a,b){return a+b}
global['add'](1,2)
它将按预期工作并且调用 add()
。
等效的 CoffeeScript 代码可以编写如下。
global=@
add=(a,b)->a+b
global['add'](1,2)
它编译为 JavaScript 为:
(function() {
var add, global;
global = this;
add = function(a, b) {
return a + b;
};
global['add'](1, 2);
}).call(this);
...但它不起作用。
Microsoft JScript runtime error: Object doesn't support this property or method
这个问题有简单的解决办法吗?
注意:
我没有在浏览器中运行代码,因此没有窗口对象。但在普通 JS 中,我始终可以通过分配
global=this
来捕获全局范围,然后从中获取函数指针。我在 CoffeeScript 中发现的一个解决方案是将所有函数声明为全局对象的成员,例如
global.add=[functionDefinition]
。但随后我必须正常将该函数调用为global.add()
。而且它的样板代码比必要的还要多。
有一个简单的黑客吗?或者有更简单的解决方案吗?
Sometimes we need to call a function by its name. I can do it in plain JavaScript as below:
global=this
function add(a,b){return a+b}
global['add'](1,2)
Which works as expected and add()
gets called.
Equivalent CoffeeScript code might can be written as below.
global=@
add=(a,b)->a+b
global['add'](1,2)
which compiles to JavaScript as:
(function() {
var add, global;
global = this;
add = function(a, b) {
return a + b;
};
global['add'](1, 2);
}).call(this);
...and it doesn't work.
Microsoft JScript runtime error: Object doesn't support this property or method
Is there an easy solution to this problem?
Note:
I am not running the code in a browser therefore there is no window object. But in plain JS I can always capture the global scope by assigning
global=this
and then get the function pointer from it.One solution in CoffeeScript I found is by declaring all functions as member of a global object like
global.add=[function definition]
. But then I have to normally call the function asglobal.add()
. And it's more boiler plate than necessary.
Is there a simple hack? Or any simpler solution?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的
add
是一个局部变量。用于将其附加到
global
对象。由于global
是脚本的全局范围,因此您仍然可以调用add
,而无需在其前面添加global.
前缀。Your
add
is a local variable. Useto attach it to the
global
object. Sinceglobal
is the global scope of your script you can still calladd
without prefixing it withglobal.
.默认情况下,CoffeeScript 编译器将每个文件包装在闭包范围内,但您可以通过添加 --bare 开关作为编译器选项来禁用此行为。
add.coffee:
当您运行:
coffee --compile add.coffee
这将产生:
现在尝试使用 --bare 开关运行它
coffee --bare --compile add.coffee
这将产生:
现在你的文件不在闭包范围内,你可以像以前那样做。
By default the CoffeeScript compiler wraps every file in a closure scope, but you can disable this behavior by adding the --bare switch as compiler option.
add.coffee:
When you run:
coffee --compile add.coffee
That will produce:
Now try run it with the --bare switch
coffee --bare --compile add.coffee
That will produce:
Now you file is not closure scoped, and you can do it the way you did it before.