3

In the following code, why can I access the variable x.b? Shouldn't it have a local scope?

CODE

function x() {
    var a = 3;
}


x.b = 8;

console.log(x.a);
console.log(x.b);

OUTPUT

undefined
8
4
  • I think because the function is an object you can access, and you just gave it a new property "b" Commented Aug 15, 2016 at 5:42
  • 1
    Both x and x.b were defined in global scope. So why do you expect them to have "local scope"? Commented Aug 15, 2016 at 5:42
  • 1
    There appears to be some fundamental misunderstanding. Dot notation does not access local variables. Commented Aug 15, 2016 at 6:00
  • 1
    You might want to be aware that you are adding a property to a function, which is probably not what you mean. Commented Aug 15, 2016 at 6:54

3 Answers 3

3

When you use var to declare a within x's constructor, a is mark as private, however when you do x.b you are essentially saying - add the property b to the object x.

Hence when you do x.b, technically speaking you are accessing object x's property b, which is 8.

Sign up to request clarification or add additional context in comments.

2 Comments

But x is not a constructor here, nor is it being used as one; it's just a plain old function.
@torazaburo correct. x is just a plain old function. I thought I saw the new keyword somewhere the last time... Hmm I must be tired :(
0

Javascript considers x.b as a global object. so you can access it even inside the function like:

x.b = 8;
function x() {
    var a = 3;
    alert(x.b)
}
x();
console.log(x.a);
console.log(x.b);

But make sure you specify x.b before function declaration.

whereas object a is specified inside the function x() which makes it private thats why you are getting undefined result for console.log(x.a);

if you write it like this:

a = 5;
function x() {
    var a = 3;
}
x.b = 8;

alert(a);
alert(x.b);

you will get results as bellow:

5
8

for javascript a and x.a are two separate objects.

Comments

0

You have defined x.b to 8 and it becomes a global var. Which means you can access it from anywhere.

So the x() is a function which has its own scope. So you can't access the vars inside a function scope in the mentioned way. However you can access the 'a' by doing this and calling the x function.

function x() {
  var a = 3;
  return a;
}

1 Comment

x.b is not a "global var". It's a property on an object called x.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.