我正在写一些带有三个类的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());
你说得对!那么如何确保正确的对象被传入构造函数呢?当我期待屋顶时,我不希望有人通过Foo对象...... – Ralph 2009-10-10 23:09:34