開発環境
- OS X El Capitan - Apple (OS)
- Emacs (Text Editor)
- JavaScript (プログラミング言語)
- Node.js(JavaScript Engine)
Eloquent JavaScript(Marijn Haverbeke 著、No Starch Press)のPart 1(Language)、Chapter 6(The Secret Life of Objects)、Exercises(A Vector Type)を取り組んでみる。
Exercises(A Vector Type)
コード(Emacs)
'use strict';
var Vector,
v1,
v2;
Vector = function (x, y) {
if (!(this instanceof Vector)) {
return new Vector(x, y);
}
this.x = x;
this.y = y;
};
Vector.prototype.plus = function (vect) {
return new Vector(this.x + vect.x, this.y + vect.y);
};
Vector.prototype.minus = function (vect) {
return new Vector(this.x - vect.x, this.y - vect.y);
};
Object.defineProperty(Vector.prototype, 'length', {
get: function () {
return Math.sqrt(Math.pow(this.x, 2) + Math.pow(this.y, 2));
}
});
v1 = new Vector(1, 1);
v2 = new Vector(-1, 1);
console.log(v1, v2);
console.log(v1.plus(v2));
console.log(v1.minus(v2));
console.log(v1.length);
console.log(v2.length);
入出力結果(Terminal, Node.js)
$ node sample1.js { x: 1, y: 1 } { x: -1, y: 1 } { x: 0, y: 2 } { x: 2, y: 0 } 1.4142135623730951 1.4142135623730951 $
0 コメント:
コメントを投稿