1

次のCoffeescriptコードを実行すると:

@sum = (x, y) -> x + y

私はこのコンパイルされたJavascriptを取得します:

(function() {

    this.sum = function(x, y) {
        return x + y;
    };

}).call(this);

Coffeescriptに何かのような任意のオブジェクトthisに置き換える方法はありますか?.call(this)myObject

4

2 に答える 2

1
myobj.sum = (x, y) -> x + y

should get compiled to (UPDATE: See Rob W's answer for compile options) :-

myobj.sum = function(x, y) {
  return x + y;
};

Isn't that what you want? So further you can call it using myobj.sum a, b

Complete code..

myobj = {}
myobj.sum = (x, y) -> x + y

alert(myobj.sum 10,4)
于 2012-08-24T09:26:57.130 に答える
1

(function() {}).call(this);はコンパイルの結果ではなく@sum = ...、実行可能ファイルによって追加されcoffeeます。これは、コンパイルの実際の結果です。

this.sum = function(x, y) {
  return x + y;
};

別の/望ましい出力を取得するには、次のコードcoffee -b -cを使用して(またはcoffee -bcまたはcoffee --bare --compile) を実行します。

(-> 
  @sum = (x, y) -> x + y
).call WHATEVER

になる

(function() {
  return this.sum = function(x, y) {
    return x + y;
  };
}).call(WHATEVER);
于 2012-08-24T09:34:30.567 に答える