JavaScript Diary

こんなのもありか [ 2001/11/25 ]

前回の続きですが、↓こんなのもありか、と思った。

// 5

Vector.prototype.add = function( p ){
    this.x += p.x ;
    this.y += p.y ;
    return this ;
};
Vector.prototype.sub = function( p ){
    this.x -= p.x ;
    this.y -= p.y ;
    return this ;
};
Vector.prototype.scale = function( v ){
    this.x *= v ;
    this.y *= v ;
    return this ;
};

ベクトルd(=(a+b)*k-c)を求めたいときは

// 5
var d = new Vector( a ).add( b ).scale( k ).sub( c );

↓のようにも書ける。

// 5'
var d = new Vector( a );
d.add( b );
d.scale( k )
d.sub( c );

速度的にはどうなんだろう、効率悪い?