Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript function variable scope

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
like image 485
max fraguas Avatar asked Jun 03 '26 06:06

max fraguas


1 Answers

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.

like image 143
Samuel Toh Avatar answered Jun 05 '26 18:06

Samuel Toh