2 回答
TA贡献1993条经验 获得超5个赞
为了访问Vehicle另一个js文件中的类,您首先需要导出该类,然后在您的js文件中导入。
script.js
import { Vehicle } from './vehicle.js';
let pickColor = prompt("Pick a color");
//let num = prompt("Pick your starting speed in mph");
let num = document.getElementById('engstart').value;
let speed = parseInt(num);
let car = new Vehicle(pickColor, 0, speed);
window.startEngine =function() {
alert(car.engineOn());
document.getElementById('displays').innerHTML += car.show() + "<br>";
}
window.accel = function() {
alert(car.accelerate());
document.getElementById('displays').innerHTML += car.accelerate();
}
window.carInBrake = function () {
alert(car.brake());
}
vehicle.js
export class Vehicle {
constructor(color, direction, currentSpeed, topSpeed, engineStarted) {
this._color = color;
this._direction = direction;
this._currentSpeed = currentSpeed;
this._topSpeed = 300;
this._engineStarted = true;
}
engineOn() {
this._engineStarted = true;
const started = `${this._color} car engine has started (VROOM VROOM!!!)`;
return started;
}
show() {
if (this._engineStarted) {
const start = `Starting Speed: ${this._currentSpeed} mph<br/>
Direction: ${this._direction}º `;
return start;
}
}
brake() {
this._engineStarted = false;
const message = "Car In Brake";
return message;
}
accelerate() {
if (this._engineStarted) {
this._currentSpeed + 10;
const current = `Accelerating. Current speed is now ${this._currentSpeed} mph.`;
return current;
}
}
left() {
let dir = this._direction;
let turn = dir - 10;
return `Turning left. direction is now ${turn} degrees`;
}
}
index.html
<div id="input">
<br />
<br />
<br />
<input type="text" id="engstart"> Pick Your Starting Speed</input>
<br />
<button onclick="startEngine()"> Start the Car </button>
<br />
<br />
<button onclick="accel()"> Accelerate </button>
<br>
<br />
<button onclick="carInBrake()"> Put Car In Brake </button>
<br />
<br />
<button onclick="left()"> Turn Left </button>
</div>
<div id="displays"></div>
<script type="module" src="./script.js"></script>
TA贡献1893条经验 获得超10个赞
问题是left()
方法中的最后一条语句。因为this._direction
是类变量并且已经定义,所以你不应该在let
那里使用关键字。只是改变-
let this._direction = newTurn;
到
this._direction = newTurn;
正如 Patrick 所指出的,return 语句也应该写在函数的末尾。
添加回答
举报