seshukumar kolli
seshukumar kolli

Reputation: 51

javascript variables returns strange outputs

I'm new here and new to Javascript. I got a strange problem here when I output the values to the console. As far as I know In both these cases the name, and the color is the properties of object car to access them we need to use this.propertyName or object.propertyName, but when I output those values to the console without using this or object name, 1st console.log returns an empty string and the other one returns the uncaught reference error. are they pointing to the window object? then in both the cases, it should return a uncaught reference, can somebody here please clarify this.. thanks in advance. :)

var car = {
    name : "ford",
    color:"red",
    log : function(){

         console.log(name);
        // outputs an empty string

         console.log(color); 
        // Returns error (this.js:8 Uncaught ReferenceError: color is not defined)

    }
}

car.log();

Upvotes: 0

Views: 62

Answers (3)

Michael Sacket
Michael Sacket

Reputation: 907

Try console.log(this.name) and console.log(this.color).

Additional Information from MDN

When a function is called as a method of an object, its this is set to the object the method is called on.

In the following example, when o.f() is invoked, inside the function this is bound to the o object.

Source: MDN

Upvotes: 4

ashish singh
ashish singh

Reputation: 6904

yes you are correct both should have thrown uncaught reference but wait ....

actually there is a property on window which is .. yeah ... name

so actually you console that property of window.. ie window.name

.. second one is just correct .. uncaught reference

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1074335

The reason you don't get a ReferenceError when outputting name is that browsers have a built-in global called name: It's the name of the current window. But they don't have a built-in global called color, so you get the error.

To access name and color on your object when you use car.log(), you'd use this.name and this.color.

Upvotes: 2

Related Questions