マックブックな日々(Macbook Geek)

Retina Macbook Proで行った設定、アプリのインストール、トラブル対策等の覚書

Illustratorのjavascriptでクラスもどきを作る

Adobe Illustratorでの制作を自動化するためScriptを使ってみた。VB, AppleScript, javascriptの3つが使えるが、WinでもMacでも使える点でjavascriptが一般的なようだ。

作業の効率化の点で不便なのは、javascriptでクラスを使う術がないことだ。
そこで、http://www.phpied.com/3-ways-to-define-a-javascript-class/を参考にして、「クラスもどき」を扱う方法を確かめてみた。

1.関数を使う

var apple = new Apple("macintosh1");
apple.color = "reddish";
alert(apple.getInfo());

function Apple (type) {
    this.type = type;
    this.color = "red";
    this.getInfo = getAppleInfo;
}
 
// anti-pattern! keep reading...
function getAppleInfo() {
    return this.color + ' ' + this.type + ' apple';
}

これでクラス的な扱いが可能。しかし、この方法は関数をグローバルとして定義するため、関数名のコンフリクトがおきる可能性がある。
そこで、次の1.1、1.2のオプションがある。

1.1 内部関数

var apple = new Apple("macintosh11");
apple.color = "reddish";
alert(apple.getInfo());

function Apple (type) {
    this.type = type;
    this.color = "red";
    this.getInfo = function() {
        return this.color + ' ' + this.type + ' apple';
    };
}


1.2 関数をユーザ側で定義

var apple = new Apple("macintosh12");
Apple.prototype.getInfo = function() {
    return this.color + ' ' + this.type + ' apple';
};
apple.color = "reddish";
alert(apple.getInfo());

function Apple (type) {
    this.type = type;
    this.color = "red";
}


2.オブジェクト・リテラルを使う

var apple = {
    type: "macintosh2",
    color: "red",
    getInfo: function () {
        return this.color + ' ' + this.type + ' apple';
    }
}
apple.color = "reddish";
alert(apple.getInfo());

この場合、「Appleクラス」を定義する必要はない。ただし、var apple={...}を、appleの呼び出しより先に定義しておかねばならない。このため、クラスや関数のような自由度がない。


3.シングルトンを使う

var apple = new function() {
    this.type = "macintosh3";
    this.color = "red";
    this.getInfo = function () {
        return this.color + ' ' + this.type + ' apple';
    };
}

apple.color = "reddish";
alert(apple.getInfo());

この方法は、1.1と似ているが、「クラス」の扱いは2と同じく、オブジェクト・リテラルになる。

          • -

個人的には1.1がもっとも混乱がないと思う。1.2は「クラス」定義後にユーザが任意の関数を加えたい場合のオプションと考えれば良いだろう。

補足:
「クラス」メソッドに引数を渡す場合は、次のように記述する。(1.1の変形)

var apple = new Apple("macintosh");
apple.color = "reddish";
alert(apple.getInfo("11"));

function Apple (type) {
    this.type = type;
    this.color = "red";
    this.getInfo = function(no) {
        return this.color + ' ' + this.type + no + ' apple';
    };
}