2015-05-06 56 views
0

我是js的新手。 我正在創建一個對象,但不知何故它不能在控制檯中給出結果。 這是我的代碼。創建對象給出意想不到的結果

var car=new object(); 
car.name="Mercedes Benz"; 
car.speed=220; 
car.showNameAndSpeed=function(){ 
console.log("The name of the car is " + car.name + " and the topspeed is " + car.speed()); 
    }; 

car.showNameAndSpeed(); 

它說對象沒有定義。我在做什麼錯?謝謝。

+4

'car.speed()'不正確。 'speed'是'car'對象的一個​​屬性,它不是一個函數。 – Claies

+3

'var car = new Object();' – Igor

+3

'var car = {};'這樣做(或者在代碼中使用大寫'O')。還要注意,「速度」不是一個函數。 – Teemu

回答

7

你的問題是,object需要大寫 - object不是在JavaScript中的東西,但Object是。

你想:

var car=new Object(); 

由於w3schools says,JavaScript的標識是區分大小寫的:

所有的JavaScript標識符區分大小寫。

變量lastNamelastname是兩個不同的變量。

所以objectObject是兩個不同的東西,你想Object - 幾乎所有的JS開始爲Object

More on Object here


而且,厄齊爾指出,你應該改變car.speed()簡單car.speed。您之前已將car.speed設置爲220,因此它不是功能。 car.speed()試圖將其視爲一個功能,這將導致問題。


所以,在所有的,這個代碼是你想要什麼:

var car=new Object(); 
car.name="Mercedes Benz"; 
car.speed=220; 
car.showNameAndSpeed=function(){ 
console.log("The name of the car is " + car.name + " and the topspeed is " + car.speed); 
    }; 

car.showNameAndSpeed(); 
2

一個更好的方式來創建一個對象,在我看來:

var car = { 
    name: "Mercedes Benz",  
    speed: 220, 
    showNameAndSpeed: function(){ 
     var self = this; 
     console.log("The name of the car is " + self.name + " and the topspeed is " + self.speed); 
    } 
} 

car.showNameAndSpeed(); //Output: The name of the car is Mercedes Benz and the topspeed is 220 

Fiddle

0

object需要大寫,car.speed()需要car.speed as speed is not a function

相關問題