Vector.prototype.setY = function(y) {
var x = this.getX();
this.d = Math.sqrt(x * x + y * y);
this.alpha = Math.atan2(y, x);
};
You can use these modified methods in exactly the same way as the original ones, and
the two lines of co de from the above example still work just the same:
v4.setX(42);
console.log(v4.getX()); //Writes 42
Note that w hat I have just showed you is not the only advantage of having special
methods for setting and quer ying the object’s properties. Using methods instead of
directly setting the values of properties also enables y ou to check th e integrity of the
values b efore setting the m. Imagine that you want to have a class representing the
natural numbers and prevent the programme r from erro neously using a negative or
non-integer numbers with that class. You can easily add this kind of checking to a
method that the programmer will use for setting values of members of the natural
number class.
I think we can now return to our Sudoku puzzle helper.
11.8 Sudoku Puzzle Helper
Professor: You already did some work o n the Sudoku helper when you implemented
a check ing of whether a numb er can be placed on th e playing grid. Our final goa l,
however, is more ambitious than that. We are going to design a web page that will
assist the visitor in solving a Sudoku pu zzle. Our product will consist of a grid of edit
boxes, into which the visitor will enter the missing numbers. Each time the entered
number conflicts with the numbers already on the puzzle board, the number will be
colored red. Apart from that, our Sudoku helper will allow the visitor to enter more
than a single number into a cell, thus creating a list of solution candidates for that cell.
We will display solution candidates sm aller and will not check whether or no t they are
placed w rongly.
Note that our program won’t attem pt to actually solve a puzzle. It will only check
whether the most recently placed number is in conflict with the nu mbers a lready on
the board, regardless of whether those numbers have been placed correctly or n ot.
Let’s now begin programming our puzzle. Because you already know enough about
objects, we can opt for object-oriented desig n. Basically, we need to identify different
objects that will help us to construct the program and then define the interactions of
these objects. Can you perhaps th ink of any par t of a Sudoku puzzle that we can
implement as an independent object?
Maria: A c ell could be an object.
Professor: Definitely. So let’s start out with a cell.
11.8. Sudoku P uzzle Help er 219