javascript コードを js2coffee で変換しても動作するコードは出力されない事がある。
手直し例を記録しておく。
動作する javascript コードとその実行結果
$ cat 1.js
function x() {
self = this;
self.v = 1;
w = 2;
self.sub = function(y) {
console.log("y=" + (y + w));
};
};
xx = new x();
console.log("xx.v=" + xx.v);
$ node 1.js
xx.v=1
y=5
js2cofee で変換して、実行してみた結果
$ js2coffee 1.js > 10.coffee
$ coffee 10.coffee
$ cat 10.coffee
xx.v=undefined
TypeError: Object function (y) {
return console.log("y=" + (y + w));
} has no method 'sub'
at Object.<anonymous> (/Users/youichikato/zzzz/10.coffee:9:1, <js>:19:6)
at Object.<anonymous> (/Users/youichikato/zzzz/10.coffee:21:4)
at Module._compile (module.js:456:26)
$ cat 10.coffee
x = ->
self = this
self.v = 1
w = 2
self.sub = (y) ->
console.log "y=" + (y + w)
xx = new x()
console.log "xx.v=" + xx.v
xx.sub 3
実行させるとエラーが発生している。
次のように coffeescript コードを編集することで、実行可能になる。
編集した coffeescript コードと、その実行結果
$ cat 11.coffee
class x
v : 1
w = 2
sub : (y) ->
console.log "y=" + (y + w)
xx = new x()
console.log "xx.v=" + xx.v
xx.sub 3
$ coffee 11.coffee
xx.v=1
y=5