Last active
January 23, 2018 03:30
-
-
Save kj786/87b819b7a7d04ac0b826 to your computer and use it in GitHub Desktop.
Implement getters and setters to ease access to private members of Vector.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*global console: true */ | |
"use strict"; | |
/* | |
A vector type | |
Write a constructor Vector that represents a vector in two-dimensional | |
space. It takes x and y parameters (numbers), which it should save to | |
properties of the same name. | |
Give the Vector prototype two methods, plus and minus, that take another vector as a parameter and return a new vector that has the sum | |
or difference of the two vectors’ (the one in this and the parameter) x | |
and y values. | |
Add a getter property length to the prototype that computes the length | |
of the vector—that is, the distance of the point (x, y) from the origin (0, | |
0) | |
*/ | |
var Vector = function(x, y) { | |
var _x = x, | |
_y = y; | |
this.getX = function() { return _x;}; | |
this.getY = function() { return _y;}; | |
this.setX = function(x) { _x = x;}; | |
this.setY = function(y) { _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); | |
}; | |
Vector.prototype.print = function(){ | |
console.log("(" + this.x + ", " + this.y + ")"); | |
}; | |
Object.defineProperty(Vector.prototype, "length", { | |
get: function () { return Math.sqrt(this.x*this.x + this.y*this.y); } | |
}); | |
Object.defineProperty(Vector.prototype, "x", { | |
set: function (x) {this.setX(x);}, | |
get: function () {return this.getX();} | |
}); | |
Object.defineProperty(Vector.prototype, "y", { | |
set: function (y) {this.setY(y);}, | |
get: function () {return this.getY();} | |
}); | |
(new Vector(1, 2)).plus(new Vector(2, 3)).print(); | |
// → Vector{x: 3, y: 5} | |
(new Vector(1, 2)).minus(new Vector(2, 3)).print(); | |
// → Vector{x: -1, y: -1} | |
console.log(new Vector(3, 4).length); | |
// → 5 | |
var test = new Vector(1, 5); | |
test.x = 30; | |
test.a = 52; | |
test.print(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment