OOP 设置方法无法正常工作

OOP set method not working properly

本文关键字:工作 常工作 设置 方法 OOP      更新时间:2023-09-26

所以我正在学习OOP。 下面的示例对我不起作用。 也想不通为什么。我将代码简化为两个变量。 我的问题真的在car1.setOdometer(1000) 当我尝试时,这条线不起作用。基本上,这条线会自动更改里程表读数变量。然后,当我单击按钮 3 时,我得到"英里"的未定义行。

.js

function Car(Make, Miles) {
    this.make = Make;
    this.odometerReading = Miles;
    this.showInfo = function() {
        alert(this.make + this.odometerReading);
    };
    this.setOdometer = function(newMiles) {
        this.odometerReading = "newMiles";
    };
}
var car1 = new Car("X", 50);
var car2 = new Car("Y", 75);
car1.setOdometerReading(1000);  //this doesn't work for me.
//It winds up changing odometerReading on car1.showInfo() from the onset!

.html

<input type="button" value="Car1" onclick="car1.showInfo()">
<input type="button" value="Car2" onclick="car2.showInfo()">
<input type="button" value="Change Car1" onclick="car1.setOdometer()">

书中的例子如上。 但是当我单击 Car1 时,更改已自动发生。 当我单击"更改 Car1",然后单击"Car1"时,我收到一条未定义的消息。

但是当我进行以下更改时,代码就可以工作了。在此处编辑"this.setOdometer":

this.setOdometer=function(newMiles){this.odometerReading=1000;}

删除

car1.setOdometerReading(1000);

是我错过了什么,还是教程书错了?

下面是工作实现的参考代码。正确设置 car1odometerReading。我猜,这些错误都是因为错别字。

<head>
<script>
function Car(Make, Miles){
    this.make = Make;
    this.odometerReading = Miles;
    this.showInfo = function() {
        alert(this.make + " " + this.odometerReading);
    }
    this.setOdometer = function(newMiles) {
        this.odometerReading = newMiles;
    }
}
var car1 = new Car("X", 50);
var car2 = new Car("Y", 75);
car1.setOdometer(1000);  //now it has the right function name and actually uses the parameter.
</script>
</head>
<body>
<input type="button" value="Car1" onclick="car1.showInfo()">
<input type="button" value="Car2" onclick="car2.showInfo()">
<input type="button" value="Change Car1" onclick="car1.setOdometer('something Else')">
</body>

我看到类汽车和汽车类型的新对象。