0

i am a newbie to js. I am creating an object but somehow it dosen't give result in console. here is my code.

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();

It says object is not defined. What am i doing wrong??Thanks.

4
  • 4
    car.speed() is incorrect. speed is a property of the car object, it's not a function.
    – Claies
    May 6, 2015 at 14:29
  • 3
    var car=new Object();
    – Igor
    May 6, 2015 at 14:29
  • 3
    var car = {}; does the trick (or use capital O in your code). Notice also, that speed is not a function.
    – Teemu
    May 6, 2015 at 14:30
  • Everyone Please enter the answer so i can upvote you.Thanks,.
    – Cloudboy22
    May 6, 2015 at 14:31

3 Answers 3

7

Your issue is that object needs to be capitalized - object isn't a thing in JavaScript, but Object is.

You want:

var car=new Object();

As w3schools says, JavaScript identifiers are case sensitive:

All JavaScript identifiers are case sensitive.

The variables lastName and lastname, are two different variables.

So object and Object are two different things, and you want Object - almost everything in JS starts as an Object.

More on Object here.


Also, as ozil pointed out, you should change car.speed() to simply car.speed. You've previously set car.speed to 220, so it's not a function. car.speed() tries to treat it as a function, which will cause issues.


So, in all, this code is what you want:

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

A better way to create an object, in my opinion:

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 needs to be capitalized and car.speed() needs to be car.speed as speed is not a function

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.