2009-10-10 105 views
0

我正在写一些带有三个类的JavaScript,一个用于屋顶,一个用于车库,另一个用于房屋。房屋类的构造函数有两个参数,一个Roof和一个Garage。当我运行这段代码,我得到:JavaScript对象构造函数的问题,其中的参数是其他对象

不能构造对象[打破这个错误]抛出新的错误(“不能构造对象”); \ 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()); 

回答

1

typeof运算符将返回"object"你的对象,而不是他们的名字。见the typeof Operator documentation

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

你可能想instanceof

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

你说得对!那么如何确保正确的对象被传入构造函数呢?当我期待屋顶时,我不希望有人通过Foo对象...... – Ralph 2009-10-10 23:09:34

1

正如里奇指出的typeof会返回 '对象',该功能不是名称。 您应该使用“构造函数”属性 。使用'instanceof'操作符。

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

Working demo →

代码:

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()); 
+0

Bobice,你是对的,最好使用instanceof。更正了答案。我不应该急于回答一个问题! :) – SolutionYogi 2009-10-10 23:17:07

+1

不要使用'constructor'。这不是标准的,在IE中不可用,并且只要你开始使用原型就不会做你的想法。在JavaScript中测试对象继承的唯一标准可靠方法是'instanceof'。 – bobince 2009-10-10 23:18:35

+0

哎呀,时态异常! (ahem) – bobince 2009-10-10 23:19:10

1

myRoofmyGarageobject类型。

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

>>myRoof isinstanceof Roof 
True