JavaScript 对象构造函数的问题,其中参数是其他对象
我正在编写一些包含三个类的 JavaScript,一个用于屋顶,一个用于车库,一个用于房屋。 house 类的构造函数有两个参数:屋顶和车库。当我运行此代码时,我得到:
无法构造对象 [Break on this error] throw new Error('can not Construction 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());
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());
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
typeof
运算符将为您的对象返回"object"
,而不是它们的名称。请参阅typeof Operator 文档。您可能需要
instanceof
:The
typeof
operator will return"object"
for your objects, not their names. See the typeof Operator documentation.You probably want
instanceof
:myRoof
和myGarage
是object
类型。如果您想检查
myRoof
是否是Roof
的实例,请使用 isinstanceof。myRoof
andmyGarage
areobject
types.If you want to check if
myRoof
is an instance ofRoof
, use isinstanceof.正如 Richie 所指出的,typeof 将返回“对象”,而不是函数的名称。
您应该使用“构造函数”属性。使用“instanceof”运算符。另外,我使用了两个“if 语句”(而不是像您那样使用一个)来根据特定错误抛出不同的错误消息。这可能意味着需要更多的代码,但是当代码损坏时,您可以确切地知道出了什么问题。
工作演示 →
代码:
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: