user8783104
user8783104

Reputation: 185

On what objects are variables within local scope of functions defined on?

So in this code below, on what object is y defined on? It outputs to three as seen below; of course var y is locally scoped, so I thought of the variable y as scoped to the object s or x. but still gives me undefined.. I know that alert(y) will give me three but that is not my question. I'm wondering on what object it is defined on if it is locally scoped in a function like the code below.

var s = function x() {
    var y = 3;
    alert(y); // y is defined on what object? //results 3
    alert(window.y); //local scope so obviously this won't be true
    alert(s.y); //undefined? why //expected 3 
    alert(x.y); //undefined? why //expexted 3
}
s();

Upvotes: 1

Views: 68

Answers (2)

xs0
xs0

Reputation: 2897

You can think of it like this - every time you call a function, a new anonymous object is created containing all of the local variables of the function.

When you say s.x, it refers to the function s (which is also its own object), but not to the anonymous object from the previous paragraph.. Note how there is only one s function, but it can be called many times, each time creating a new anonymous object.

Here's how your code actually looks* behind the scenes:

var s = function x(_ctx) {
   _ctx.y = 3;
   alert(_ctx.y); // locals are looked up in _ctx
   alert(window.y); // 
   alert(s.y); // not looking in _ctx, but in s
   alert(x.y); // ditto, as x === s
}

s({});

*) well, in a way..

Upvotes: 3

Suren Srapyan
Suren Srapyan

Reputation: 68655

y in declared in the scope of function x. It is not related to any object. s is the same x. It refers to a function. Functions are callable objects which can have it's own properties assigning via s.y or x.y, but everything which is declared in it via var, const, let or function is not related to its object itself, but it's context. So the y is a simple variable, just scoped in the context of the function.

Upvotes: 2

Related Questions