我正在编写一些包含三个类的 JavaScript,一个用于屋顶,一个用于车库,一个用于房屋。 house 类的构造函数有两个参数:屋顶和车库。当我运行此代码时,我得到:
无法构造对象[中断此错误] throw new Error('无法构造对象');\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());
最佳答案
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)) {
...
关于javascript - JavaScript 对象构造函数的问题,其中参数是其他对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1549321/