开发者

Calling a function by its name

开发者 https://www.devze.com 2023-03-16 02:06 出处:网络
Sometimes we need to call a function by its name. I can do it in plain JavaScript as below: global=this

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:

  1. I am not running the code in a browser therefore there is no window object. B开发者_JAVA百科ut in plain JS I can always capture the global scope by assigning global=this and then get the function pointer from it.

  2. 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 as global.add(). And it's more boiler plate than necessary.

Is there a simple hack? Or any simpler solution?


Your add is a local variable. Use

@add=(a,b)->a+b

to attach it to the global object. Since global is the global scope of your script you can still call add without prefixing it with global..


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:

add = (a,b) -> a+b

When you run: coffee --compile add.coffee

That will produce:

(function() {
  var add;
  add = function(a,b) {
    return a+b;
  };
}).call(this);

Now try run it with the --bare switch coffee --bare --compile add.coffee

That will produce:

var add;
add = function(a, b) {
  return a + b;
};

Now you file is not closure scoped, and you can do it the way you did it before.

0

精彩评论

暂无评论...
验证码 换一张
取 消