0

我正在编写一些带有三个类的 JavaScript,一个用于屋顶,一个用于车库,一个用于房屋。house 类的构造函数有两个参数,一个 Roof 和一个 Garage。当我运行此代码时,我得到:

无法构造对象 [Break on this error] throw new Error('can notconstruct object');\n

在 Firebug 中,即使对象显然是正确的类型。知道我做错了什么吗?这是代码:

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());
4

3 回答 3

1

运算符将typeof返回"object"您的对象,而不是它们的名称。请参阅typeof 运算符文档

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

你可能想要instanceof

function House(roof, garage) {
    if (!(roof instanceof Roof) || !(garage instanceof Garage)) {
    ...
于 2009-10-10T23:04:33.500 回答
1

正如 Richie 所指出的,typeof 将返回“对象”,而不是函数的名称。您应该使用“构造函数”属性。使用“instanceof”运算符。

此外,我使用了两个“if 语句”(而不是像您那样使用一个)来根据特定错误抛出不同的错误消息。这可能意味着更多的代码,但是当代码中断时,您确切地知道出了什么问题。

工作演示 →

代码:

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());
于 2009-10-10T23:08:21.837 回答
1

myRoof并且myGarageobject类型。

如果要检查是否myRoof是 的实例Roof,请使用 isinstanceof。

>>myRoof isinstanceof Roof
True
于 2009-10-10T23:11:59.443 回答