| Yoshiki's notes | |||||||||||||||||||||||||||||||||||||||||||||||
|
Subscribe
Flavours
Categories
|
Mon, 08 Aug 2005
JavaScript オブジェクト指向
JavaScript を使っていて中々怪しげな感じを受けるのが、"this" というものである。
他のものはすべて lexical に bind されるくせに、this だけは dynamic に
bind される。オブジェクト指向もどきをするときに、
function Point(x, y) {
this.x = x;
this.y = y;
}
Point.prototype.distance = function() {
return Math.sqrt(this.x * this.x + this.y + this.y);
}
p = new Point(x, y);
document.write(p.distance());
とオブジェクト指向っぽく書くときの p.distance っていうのは ただの syntax sugar であり、 Point.prototype.distance.call(p) と等価である。this は call の第一引数が bind される。 これは実質的には (put 'Point 'distance (lambda (x y) (+ (* x x) (* y y)))) (funcall (get 'Point 'distance) 2 3) とやってるのと何ら変わらない (ちょっと手抜きしたので this がないけど)。 JavaScript では prototype っていう連想配列に anonymous function を突っこんでるだけ。Lisp もどきのはちゃんと Common Lisp しらべて declare special かなんかで dynamic binding の this を 作れば本当に同じものができそうな気がする。というわけで、 結局の所私としては 常に dynamic binding される this という変な変数のある Lisp として書けば別にどうってことは無いのであった。 |
||||||||||||||||||||||||||||||||||||||||||||||