HTML and CSS Reference
In-Depth Information
delete circle.radius;
assertEquals(6, circle.radius);
}
});
Defining the object and constructor this way works because of the way con-
structors work. If a constructor returns an object rather than a primitive value, it will
not create a new object as this . In those cases, the new keyword is just syntactical
fluff. As the example in Listing 8.13 shows, simply calling the function works just
as well.
Listing 8.13 Using Circle without new
"test omitting new when creating circle": function () {
var circle = Circle(3);
assert(circle instanceof Circle);
assertEquals(6, circle.diameter);
}
The prototype property is a convention used with constructors in order for
the new keyword to work predictably. When we are creating our own objects and
setting up the prototype chain ourselves, we don't really need it. Listing 8.14 shows
an example in which we leave constructors, new and instanceof behind.
Listing 8.14 Using Object.create and a function
"test using a custom create method": function () {
var circle = Object.create({}, {
diameter: {
get: function () {
return this.radius * 2;
}
},
circumference: { /* ... */ },
area: { /* ... */ },
create: {
value: function (radius) {
var circ = Object.create(this, {
radius: { value: radius }
});
return circ;
 
Search WWH ::




Custom Search