![](http://images-20200215.ebookreading.net/24/3/3/9781498731454/9781498731454__start-programming-using__9781498731454__bged.png)
Professor: This isn’t a problem in this particular c ase. Because the max() method is
being defined as an instance metho d of the Array class, the method is never accessible
without an objec t reference. Hence, if you want to access the ma x() method from
within the same me thod, you sho uld use the expression th is.max().
Maria: I see. Can we test our ma x() method to see how it works?
Professor: No problem . Here are some examples:
var a1 = [7, 3, 8, -1, 99, 5];
var a2 = [];
var a3 = [5, "w", 66, 2];
var a4 = [-3, -12, ""];
console.log(a1.max()); //Writes 99
console.log(a2.max()); //Writes -Infinity
console.log(a3.max()); //Writes NaN
console.log(a4.max()); //Writes 0
Before we continue, I should mentio n that it is not always possible to add methods
in this way to classes implemented by differ ent host environme nts, like browsers, for
example. These are classes th at are not defined by th e core JavaScript language and
are characterized as part o f client-side JavaScript in the JavaScript reference at the end
of the book.
11.7 More on Setting and Querying Object Properties
Professor: One of the key concepts in the object-or ie nted programmin g paradig m is
encapsulation, which, formally, bears more than a single meaning. One definition of
encapsulation is that it is a mechanism for information hiding. In practice this means
that the intern al representation of a n object is separated and hidde n from a programmer
who uses the object. Take, for example, our Vector class. The class is in te rnally
represented by the Cartesian coordinates x and y, but that need not always be the case.
You could just as well decide to store vectors in polar form. In order to hide that detail
from the programmer, you can provide special meth ods that allow the programme r
to access the object data indirectly. If the object’s internal data representation ever
changes, then you simply reprogram the access methods to perform necessary data
transform ations so tha t they can be used in exactly the same way as they had been
before the change.
For example, if you want to w rite the value of the x component of the v4 vector from
the example on page 214 to the JavaScript Console, you currently have no other op tion
but to access the component directly:
console.log(v4.x);
That is not such a good idea, tho ugh, especially when direct access like this one is
sprinkled all over the co de. Consider, for example, that you write, or even g et from
another autho r the new version of the Ve ctor class, w hose internal repre sentation of
11.7. More on Setti ng and Querying Object Properties 217