2016-01-23 44 views
-3

所以我正在學習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); 

我缺少的東西,或者是教程書只是錯了嗎?

+2

這段代碼是否缺少從'function Cars(Make,Miles)開始的右括號{'?此外,該函數名稱錯誤,它應該是'Car'而不是'Cars'。 –

+2

setOdometerReading()沒有在任何地方定義。 – Prashant

+2

你有複製粘貼這個從某個地方或手寫?有錯誤的函數名稱和其他小錯誤。仔細檢查一切。使用你的[瀏覽器的開發工具](http://www.creativebloq.com/javascript/javascript-debugging-beginners-3122820)。 – ekuusela

回答

1

這裏是工作實現的參考代碼。正確設置odometerReadingcar1。我想,錯誤只是因爲錯別字。

<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> 
+0

事情是50永遠不會要求car1。它應該是make x和miles 50並使用該參數,以便它不需要用於onclick事件。 – chignon

+0

'odometerReading = 50'通過調用'setOdometer(1000)'立即覆蓋。如果你離開這條線,它的值將是'50'。我有'setOdometer()'使用參數,因爲它實際上是一個setter函數,將它設置爲靜態字符串對我來說沒有意義。 –

1

我看到類汽車和類型車的新對象。

+0

它應該是汽車。對不起 – chignon