HTML and CSS Reference
In-Depth Information
Because Object.defineProperties and, by extension, Object.
defineProperty cannot be fully simulated in ES3 environments, this is not
usable, but it shows how Object.create works. Also note that ES5 allows the
prototype to be null , which is not possible to emulate across browsers in ES3.
An interesting side-effect of using Object.create is that the instanceof
operator may no longer provide meaningful information, as the native Object.
create does not use a proxy constructor function to create the new object. The
only function of which the newly created object will be an instance is Object .
This may sound strange, but instanceof really isn't helpful in a world in which
objects inherit objects. Object.isPrototypeOf helps determine relationships
between objects, and in a language with duck typing such as JavaScript, an object's
capabilities are much more interesting than its heritage.
8.2.3 Getters and Setters
As stated in the previous section, Object.defineProperty cannot be reliably
emulated in ES3 implementations, because they do not expose property attributes.
Even so, Firefox, Safari, Chrome, and Opera all implement getters and setters,
which can be used to solve part of the defineProperty puzzle in ES3. Given
that it won't work in Internet Explorer until version 9 1 , getters and setters won't be
applicable to the general web for still some time.
Getters and setters make it possible to add logic to getting and setting properties,
without requiring change in client code. Listing 8.10 shows an example in which
our circle uses getters and setters to add a virtual diameter property.
Listing 8.10 Using getters and setters
"test property accessors": function () {
Object.defineProperty(circle, "diameter", {
get: function () {
return this.radius * 2;
set: function (diameter) {
if (isNaN(diameter)) {
throw new TypeError("Diameter should be a number");
this.radius = diameter / 2;
1. Internet Explorer 8 implements Object.defineProperty , but for some reason not for client
Search WWH ::

Custom Search