所以我正在學習OOP。下面的例子對我不起作用。並不知道爲什麼。我將代碼簡化爲兩個變量。我的問題真的在car1.setOdometer(1000)
這條線在我嘗試時不起作用。基本上這條線自動改變OdometerReading變量。然後,當我點擊按鈕3時,我會得到'Miles'的未定義行。OOP設置方法不正常
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);
我缺少的東西,或者是教程書只是錯了嗎?
這段代碼是否缺少從'function Cars(Make,Miles)開始的右括號{'?此外,該函數名稱錯誤,它應該是'Car'而不是'Cars'。 –
setOdometerReading()沒有在任何地方定義。 – Prashant
你有複製粘貼這個從某個地方或手寫?有錯誤的函數名稱和其他小錯誤。仔細檢查一切。使用你的[瀏覽器的開發工具](http://www.creativebloq.com/javascript/javascript-debugging-beginners-3122820)。 – ekuusela