🍃このブログは移転しました。
3秒後、自動的に移動します・・・。

0からはじめるJSX Part.6

JSXネタを投稿し出してから、RTされたりはてブがつくようになりまして。
なんだか嬉しい反面、見られてると思うと、こんなにわかの怪しい独自解釈情報を拡散して良いのかなぁっていう微妙な心境にも・・。

25年間で得た知識を総動員して理解に励んでおりますが、いかんせん間違いもあると思います。
ばしばしツッコミもお待ちしてますので、なにとぞ、なにとぞ。

関数とクロージャ

In JSX, functions are first-class objects and they have static types. You can declare a variable of a function type like var f : function(arg : number) : number, a function that takes a number as an argument and returns another number (or, just returns the same value as the argument; but it's not important here). The variable f can be called as f(42) from which you will get a number value.

JSXでのfunctionは第一級オブジェクトとして扱われ、型を持ちます。

var f = function(arg: number): number{
  // ...
}

このように宣言することができ、f(42)のようにいつでも呼び出すことができます。

It is possible to define closures (or anonymous functions). They are typically used to implement event listeners, which are popular in GUI programming. Closures are similar to JavaScript except for what this points at: when a closure is defined within a member function, it refers to the receiver of the member function. See the following example.

クロージャや匿名関数を使うことも可能です。
GUIプログラミングでよく使われるイベントリスナの実装に使われるものです。
JavaScriptのクロージャとの違いは、thisが指すものくらいです。
メンバー関数として定義されたクロージャは、そのメンバー関数を持つクラスを指します。
↑あってる・・かな?

class _Main {
  var foo = 42;

  function constructor() {
    var f = function() : void {
      log this.foo; // thisは_Main
    };

    f(); // says 42
  }

  static function main(args : string[]) : void {
    var o = new _Main();
  }
}

クロージャは前に記事も書きました。
JavaScriptのクロージャについて
おそらくJavaScriptとしての記法や仕様は同じようなものだと思うのですが、いかんせんクロージャ自体の使い道や利用シーンが想像できないので、現時点ではなんとも・・。

今回は短いのでもうひとつ。

モジュール機構

JSX has a module system. You can reuse JSX class libraries by the import statement. For example, the following program uses timer.jsx module, which exports the Timer class.

JSXには、外部で記述したクラスを、モジュールとしてインポートする仕組みがあります。

import "timer.jsx";

class _Main {

  static function main(args : string[]) : void {

    Timer.setTimeout(function() : void {
      log "Hello, world!";
    }, 1000);

  }

}

A module may export multiple classes, but you can specify what modules you import or name a namespace which the module is imported into.

この例では、timer.jsxをインポートすることで、Timerクラスを利用しています。
どのモジュールをインポートするかは、intoでネームスペースを指定することで制御できます。

// 063.import-by-name/foo.jsxをインポート
import "063.import-by-name/foo.jsx";
// 063.import-by-name/foo.jsxから、_Private1, _Private2の2クラスをインポート
import _Private1, _Private2 from "063.import-by-name/foo.jsx";
// 063.import-by-name/foo.jsxから、_Private3クラスをfooクラスとしてインポート
import _Private3 from "063.import-by-name/foo.jsx" into foo;

class Test {

  static function run() : void {
    _Private1.say();
    _Private2.say();
    foo._Private3.say();
  }

}
  • "_"ではじまるクラスは、インポートされない。
  • fromとクラス名を指定して、インポートすることもできる。
  • into [特定の変数]で、インポートすることもできる。

もちろんインポートした時にクラス名が被ってたらエラー、自ファイルをインポートするのもエラーなど、きっちりしてます。

大規模開発っぽい!
どういう単位でファイルを分けるべきとか、そういうのも勉強しなきゃならんですね。

次回で一応最後です。