expert
expert

Reputation: 30085

Global variable is not so global in Chrome

I'm learning JavaScript and going through this tutorial on jQuery's website.

In following example

    // A function being attached to an object at runtime
    var myName = "the global object";
    var sayHello = function ()
    {
        console.log("Hi! My name is " + this.myName);
    };
    var myObject = {
        myName: "Rebecca"
    };
    var secondObject = {
        myName: "Colin"
    };

    myObject.sayHello = sayHello;
    secondObject.sayHello = sayHello;

    sayHello();              // "Hi! My name is the global object"
    myObject.sayHello();     // "Hi! My name is Rebecca"
    secondObject.sayHello(); // "Hi! My name is Colin"

I don't see expected output when sayHello() is invoked. Instead variable is undefined. But if I define global variable by assigning it to window.myName it works.

I'm using Chrome Version 25.0.1364.152 m.

Is tutorial incorrect or am I missing something ?

Full HTML is here: http://pastebin.com/4M27vDB4

UPDATE: Accepted answer explains what happened. I also want to mention possible solution - declaring global variable above without var. Because of following:

Furthermore, variables that are declared inside a function without the var keyword are not local to the function — JavaScript will traverse the scope chain all the way up to the window scope to find where the variable was previously defined. If the variable wasn't previously defined, it will be defined in the global scope, which can have unexpected consequences.

Upvotes: 3

Views: 3822

Answers (2)

Jitesh Tukadiya
Jitesh Tukadiya

Reputation: 1339

in your program you have used this.myName. this keyword is used to point current object. when you call only sayHello() then in that case "this" means "window" because default current object is window. Now you have not defined window.myName then it will give "undefined".

Upvotes: 3

dfsq
dfsq

Reputation: 193251

You have put this code inside

$(document).ready(function ()
    // ...
}); 

closure. In this case context inside it will not be window (it will be document object) and you will get undefined as you describe.

Upvotes: 4

Related Questions