我是新手javascript程序员,我正在尝试创建一个小文本游戏。基本上,用户应该在提示时键入船名,并根据他们选择的船只将他们停靠在港口。问题是我似乎无法让我的if语句正常工作,以便正确使用ShipTypes的对象。任何帮助将不胜感激。
这是我的代码:
window.alert("Greetings sea traveller. You have sailed many long days across the ocean and now it is time to dock your ship into port. But you must choose the correct mooring for the size of your vessel.");
window.prompt("Please choose from the following ships: Carrier, Destroyer, or a Sloop" .toLowerCase());
var harbor = 30;
function ShipType (shipName,shipType,shipLength,shipHull,shipKeelDepth) {
"use strict";
this.shipName = shipName;
this.shipType = shipType;
this.shipLength = shipLength;
this.shipHull = shipHull;
this.shipKeelDepth = shipKeelDepth;
}
var carrier = new ShipType ("The Enterprise","Carrier",200,"Steel",80);
var destroyer = new ShipType ("The Dragon","Destroyer",170,"Steel",65);
var sloop = new ShipType ("The Sunray","Sloop",120,"Hybrid",25);
/*window.alert(sloop.shipKeelDepth);*/
if(ShipType.shipKeelDepth <= harbor){
window.alert("You may enter the harbor! ");
}
else {
window.alert("You may not enter our harbor as your ship is the wrong size!");
}
答案 0 :(得分:4)
您正在尝试访问构造函数的属性。 您需要在该构造函数的实例上访问它。
编辑以帮助您在下面发表评论。 “如果我有100艘船怎么办?”
那当然会很棒。无论如何,你可以像你这样在你的构造函数上放一个方法:
您还需要跟踪海港的一些方式,无论是在模型本身还是其他地方。
ShipType.prototype.checkKeelDepth = function () {
if (this.shipKeelDepth <= this.harbor) {
// do something
}
}
const someShipType = new ShipType(...args)
someShipType.checkKeelDepth()
答案 1 :(得分:2)
尝试在if语句中使用其中一个实际的发货名称。例如:
if(carrier.shipKeelDepth <= harbor){
window.alert("You may enter the harbor! ");
}
答案 2 :(得分:1)
您正在呼叫ShipType
constructor
而非object
你可以做以下事情
if(carrier.shipKeelDepth <= harbor){
window.alert("You may enter the harbor! ");
}
或
if(destroyer.shipKeelDepth <= harbor){
window.alert("You may enter the harbor! ");
}
或
if(sloop.shipKeelDepth <= harbor){
window.alert("You may enter the harbor! ");
}