Skip to content

Instantly share code, notes, and snippets.

@wcang
Last active August 29, 2015 14:12
Show Gist options
  • Select an option

  • Save wcang/2ab086812e0d89fc3786 to your computer and use it in GitHub Desktop.

Select an option

Save wcang/2ab086812e0d89fc3786 to your computer and use it in GitHub Desktop.
Javascript Object Orientation with getter function
// Your code here.
function Vector(x, y) {
this.x = x;
this.y = y;
this.plus = function(v) {
var res = new Vector(this.x, this.y);
res.x += v.x;
res.y += v.y;
return res;
}
this.minus = function(v) {
var res = new Vector(this.x, this.y);
res.x -= v.x;
res.y -= v.y;
return res;
}
this.toString = function() {
return "Vector{x: " + this.x + ", y: " + this.y + "}";
}
/* the following is invalid in javascript, what a weird language */
/*
get length() {
return Math.sqrt(Math.pow(this.x, 2) + Math.power(this.y, 2));
}*/
}
Vector.prototype = {
get length() {
return Math.sqrt(Math.pow(this.x, 2) + Math.pow(this.y, 2));
}
}
console.log(new Vector(1, 2).plus(new Vector(2, 3)));
// → Vector{x: 3, y: 5}
console.log(new Vector(1, 2).minus(new Vector(2, 3)));
// → Vector{x: -1, y: -1}
console.log(new Vector(3, 4).length);
// → 5
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment