Sandy Gifford
Sandy Gifford

Reputation: 8136

Scope on Object not Behaving as Expected

I'm trying to clean up a long-standing bad habit in coding: Writing widgets to the global scope.

I've made a large, mostly self-contained script for a news roll on a webpage and was pleasantly surprised at how well it worked after I stuffed the whole thing into a function... TOO well in fact.

To ensure I wasn't cheating, I wrote the following code to make sure my scoping was correct:

var story_count = "THIS IS NOT A NUMBER";

console.log(story_count);

touch_roll = function()
{
    this.story_count = 0;
}

console.log(story_count);

touch_roll();

console.log(story_count);

Fully expecting this to yield the following response in the console

THIS IS NOT A NUMBER
THIS IS NOT A NUMBER
THIS IS NOT A NUMBER

I was entirely surprised to find the output was, in fact, this:

THIS IS NOT A NUMBER
THIS IS NOT A NUMBER
0

Is this not what I think it is? Research hasn't really helped, but I'm a little burnt out so it's entirely possible I'm reading it all wrong. If not this, then how DO I keep all of my namespaces completely within the scope of that function so as not to mess with existing bits on the site?


As per Matt's answer below, here is the corrected code:

var story_count = "THIS IS NOT A NUMBER";

console.log(story_count);

var touch_roll = new function()
{
    this.story_count = 0;
    console.log(story_count);
}

console.log(story_count);

By declaring touch_roll as a var and instantiating the function as new Javascript evaluates said function into an object as run-time (so we can also remove the call to touch_roll() at the bottom).

The corrected output is as follows:

THIS IS NOT A NUMBER
0
THIS IS NOT A NUMBER

Upvotes: 0

Views: 47

Answers (1)

Matt
Matt

Reputation: 75317

Because you're not invoking touch_roll with new, this is the window object (which is what global variables in browser environments belong to).

If you were to use new, then you'd get:

THIS IS NOT A NUMBER
THIS IS NOT A NUMBER
THIS IS NOT A NUMBER

Additionally, you're declaring touch_roll as a implicit global variable. Either use function declaration syntax, or add a var to it.

Upvotes: 4

Related Questions