Question

I'm writing some JavaScript with three classes, one for Roofs, one for Garages, and one for Houses. The house class takes two arguments to its constructor, a Roof and a Garage. When I run this code I get:

can not construct object [Break on this error] throw new Error('can not construct object');\n

in Firebug even though the objects are clearly of the right type. Any idea what I'm doing wrong? Here's the code:

function Roof(type, material) {
     this.getType = function() { return type; }
     this.getMaterial = function() { return material; }
}

function Garage(numberOfCars) {
     this.getNumberOfCars = function() { return numberOfCars; }
}

function House(roof, garage) {
     if (typeof roof !== 'Roof' || typeof garage !== 'Garage') {
          throw new Error('can not construct object');
     }

     this.getRoof = function() { return roof; }
     this.getGarage = function() { return garage; }
}

myRoof = new Roof("cross gabled", "wood");
myGarage = new Garage(3);
myHouse = new House(myRoof, myGarage);
alert(myHouse.getRoof().getType());
Was it helpful?

Solution

The typeof operator will return "object" for your objects, not their names. See the typeof Operator documentation.

function House(roof, garage) {
    alert(typeof roof);   // "object"
    ...

You probably want instanceof:

function House(roof, garage) {
    if (!(roof instanceof Roof) || !(garage instanceof Garage)) {
    ...

OTHER TIPS

myRoof and myGarage are object types.

If you want to check if myRoof is an instance of Roof, use isinstanceof.

>>myRoof isinstanceof Roof
True

As noted by Richie, typeof will return 'object', not the name of the function. You should use the 'constructor' property. Use 'instanceof' operator.

Also, I have used two 'if statements' (instead of one, like you did) to throw different error message based on the particular error. This may mean a little more code, but when the code breaks, you know exactly what went wrong.

Working demo →

Code:

function Roof(type, material) {
     this.getType = function() { return type; }
     this.getMaterial = function() { return material; }
}

function Garage(numberOfCars) {
     this.getNumberOfCars = function() { return numberOfCars; }
}

function House(roof, garage) {
     if (roof instanceof Roof)
     {
        throw new Error('Argument roof is not of type Roof');
     }

     if(garage instanceof Garage) 
     {
          throw new Error('Argument garage must be of type Garage.');
     }

     this.getRoof = function() { return roof; }
     this.getGarage = function() { return garage; }
}

myRoof = new Roof("cross gabled", "wood");
myGarage = new Garage(3);
myHouse = new House(myRoof, myGarage);
alert(myHouse.getRoof().getType());
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top