HTML and CSS Reference
In-Depth Information
7.2.2 Creating Objects with new
When a function is called with the new operator, a new JavaScript object is created.
The function is then called using the newly created object as the this value along
with any arguments that were passed in the original call.
In Listing 7.13 we see how creating objects with constructors compares with
the object literal we've been using so far.
Listing 7.13 Creating objects with constructors
function Circle(radius) {
this.radius = radius;
// Create a circle
var circ = new Circle(6);
// Create a circle-like object
var circ2 = { radius: 6 };
The two objects share the same properties—the radius property along with
properties inherited from Object.prototype . Although both objects inherit
from Object.prototype , circ2 does so directly (i.e., its [[Prototype]] prop-
erty is a reference to Object.prototype ), whereas circ does so indirectly
through Circle.prototype . We can use the instanceof operator to deter-
mine the relationship between objects. Additionally, we can use the constructor
property to inspect their origin, as seen in Listing 7.14.
Listing 7.14 Inspecting objects
TestCase("CircleTest", {
"test inspect objects": function () {
var circ = new Circle(6);
var circ2 = { radius: 6 };
assertTrue(circ instanceof Object);
assertTrue(circ instanceof Circle);
assertTrue(circ2 instanceof Object);
assertEquals(Circle, circ.constructor);
assertEquals(Object, circ2.constructor);
Search WWH ::

Custom Search