Doge log

Abby CTO 雑賀 力王のオフィシャルサイトです

prototypeというかscopeのトップレベルの関数を作成する

真面目な人はsetPrototypeを使うんだけど。
今回はAssertをトップレベル関数にしてみる。
理由はJsUnitコンパチなテストケースを作成したいから。
従来は

//PrototypeはScriptableを実装したクラス
ScriptableObject scope = cx.initStandardObjects();
Scriptable prototype = new Prototype();
scope.setPrototype(prototype);

こうやって書くんだろうけど大量にトップレベル関数を作るとなるとめんどい。
真面目にNativeFunctionなんか継承したりすると嫌になる。
チョンボする。jsでやっちまえと。

String assert = "var assert = Packages.junit.framework.Assert; for(var v in assert){ this[v] = assert[v];}";
cx.evaluateString(global, assert, "assert", 0, null);

めんどいからthisにぶらさげるコードを書いてeval。
こうすると

function testFunction2(){
		java.lang.System.out.println('TEST1');
		assertEquals(true, true);
		//assertEquals(true, true);
}

function testFunction1(){
		java.lang.System.out.println('TEST2');
		assertEquals(true, true);
		//assertEquals(true, true);
}

これで動くようになる。

ちなみに

this.prototype = assert.prototype;

ではうまくいかないようです。
うくく。