Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript local variable works like class variable in window

I find this behavior of the global window object a little weird.

var x = 10;
function SomeClass(){
    var y = 15;
    console.log("Someclass:y - " + this.y); //prints undefined
}

console.log("window.x: " + window.x);   //prints 10

var obj = new SomeClass();
console.log("obj.y: " + obj.y); //prints - undefined

Both variables x and y are local (to window and to SomeClass respectively). Despite calling y from an object context, it only prints undefined - presumably because that is how local variables are supposed to behave. But window.x behaves differently by printing value of x. I understand that this is how you create global varibles but is this a special property of window that makes local variables behave like object variables?

like image 757
Ara Avatar asked Mar 24 '26 10:03

Ara


2 Answers

According to the ECMAScript language specification:

If the variable statement occurs inside a FunctionDeclaration, the variables are defined with function-local scope in that function, [...]. Otherwise, they are defined with global scope (that is, they are created as members of the global object [...])

Essentially this means the var keyword has a slightly different meaning inside a function and in the global scope.

I think one way to look at it is that creating a variable in global scope is more like setting an instance variable on an object after it is created than like setting a local variable.

Compare setting a local variable in the constructor:

function SomeClass(){ 
    var y = 15; 
} 

var obj = new SomeClass(); 
console.log("obj.y: " + obj.y); //prints - undefined 

and setting a instance variable after the object is created:

function SomeClass(){ 
} 

var obj = new SomeClass(); 
obj.y = 15;
console.log("obj.y: " + obj.y); //prints - 15
like image 163
Mario Menger Avatar answered Mar 25 '26 23:03

Mario Menger


in order to achieve what you are trying to with var y, it should be this.y = 15; That will allow you to reference it via this.y but also obj.y The reason it is printing undefined is simply because y is not assigned to be a member of SomeClass, just as a random variable within it.

http://www.javascriptkit.com/javatutors/object.shtml

like image 26
Angelo R. Avatar answered Mar 25 '26 23:03

Angelo R.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!