2008年 11月 の投稿一覧

その後

電車を寝過ごす。
飲み過ぎたのだもの。

id:maruta3 と鍋を食べに行く。
生ビールを3杯。日本酒を1合。ウイスキーを1杯。ジントニックを1杯。
馬鹿じゃないの?というくらい飲む。

飲み放題だもの。

f:id:hideack:20081107234643j:image

どーでもいい話

他の会社のエンジニアの人と私の雑談。

(前略)
先方「タイプあるんですか?」
私「"うただひかる"とかタイプかも。」
先方「あぁ、好きそうですねぇ。なんとなくわかるなぁ。」

わかるものなのか。
どこでわかったんだろ?

prototype.js bindメソッド

昨日の続き。

this.timer =  new PeriodicalExecuter(this.showCounter, 2);

と書いたときに何故未定義のエラーになったか。
prototype.jsのPeriodicalExecuterクラスのコンストラクタの定義を見ると、

PeriodicalExecuter:[constructor](callback, interval)

引数名 内容
callback a function that will be passed the PeriodcalExecuter object itself as the only argument
interval the interval (in seconds)

となっている。
第一引数には、関数オブジェクトを渡してあげないとならない。
が、JavaScriptの場合、上の様な書き方をするとthisは関数オブジェクトを呼び出したときにその関数オブジェクトを格納していたインスタンスを指し、このタイマーが収められているインスタンスを指さない。
(書いている人=私は指してるつもりだったのだけど)

で、ここでprototype.jsの拡張、"bind"メソッドを使う。

this.timer =  new PeriodicalExecuter(this.showCounter.bind(this), 2);

と書く事によって、thisが指す先を束縛することができる。bindの引数には束縛するインスタンスを指定する。
ここでは、自身のクラスから生成されたインスタンスを指すので 〜.bind(this) とすることで問題が解決した。

…ややこしいなぁ。まだ、「なんとなく」わかった状態だ。
絵に描いたらわかるかなぁ。と思ってノートにメモ書きしてみたけど、ますます混乱…。

委譲とPeriodicalExecuterとprototype.jsと。

とりえあずサンプル。
次の様なHTMLと...

<html>
<head>
	<script type="text/javascript" src="prototype.js"></script>
	<script type="text/javascript" src="mainctrl.js"></script>
	<script type="text/javascript">
		//<![CDATA[
		var mainctrl = new Mainctrl();
		// ]]>
	</script>
	</head>
<body>
<input type="button" onclick="mainctrl.start();" value="start"/><br/>
<br/>
<input type="button" onclick="mainctrl.stop();" value="stop"/><br/>
<hr>
<div id="status">
</div>
</body>
</html>

次の様なJavaScript

var Mainctrl = Class.create();
Mainctrl.prototype = {
counter : 0,
timer : null,
initialize : function(){
this.timer =  new PeriodicalExecuter(this.showCounter.bind(this), 2); // ← 委譲
this.timer.stop();
},
start : function(){
this.timer.registerCallback();
},
stop : function(){
this.timer.stop();
},
showCounter : function(){
this.counter = this.counter + 1;
$('status').innerHTML = this.counter;
}
};

で、ポイントは、

this.timer =  new PeriodicalExecuter(this.showCounter.bind(this), 2); // ← 委譲

である。
ここを、

this.timer =  new PeriodicalExecuter(this.showCounter(), 2);

この様に書くとエラーとなる。

this.callback is not a function

以後、後日へ続く。(あは

パーソントリップ調査

東京都から粗品ボールペン入りで封筒が届いていたので回答。
と、真面目に回答票に記入しようとしたのだけど、ホームページで回答OKということなので回答。
営業の人は大変だろうけど、私の場合は朝起きて勤務先に行って家に戻るというパターン。

少々手間だったけど、まぁ、多少なりとも役に立つのであれば。