Yoshiki's notes
   


About
Open source software, shogi and my life outside of workplace.

Yoshiki Hayashi

Subscribe
RSS

Flavours

  • index
  • circa 1993
  • RSS
  • August
    Sun Mon Tue Wed Thu Fri Sat
     
    8
         


    Categories

           
    Mon, 08 Aug 2005

    JavaScript オブジェクト指向
    まぁ、食わず嫌いも何なのでいろいろといじってみた JavaScript であるが、やっぱり 変な言語だなぁという感想は変わらない。いろいろ怪しい変なことのできる言語と いうのは発見だけど。

    JavaScript を使っていて中々怪しげな感じを受けるのが、"this" というものである。 他のものはすべて lexical に bind されるくせに、this だけは dynamic に bind される。オブジェクト指向もどきをするときに、 function() {this.property = whatever;} などとするときは、 foo.bar() の foo が this に bind されるし、event handler で同じように this を使うと DOM の element が this に 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 として書けば別にどうってことは無いのであった。

    [] permanent link