Javascript local variable works like a class variable in a window

I find this behavior of the global window object a bit strange.

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 x and y are local (for the window and for SomeClass, respectively). Despite calling y from the context of the object, it prints only undefined - presumably because that is how local variables should behave. But window.x behaves differently by printing the value of x. I understand that this is how you create global variables, but is this a special property of a window that causes local variables to behave like object variables?

+3
source share
4 answers

ECMAScript:

FunctionDeclaration, - , [...]. (.. [...])

, , var .

, , , .

:

function SomeClass(){ 
    var y = 15; 
} 

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

:

function SomeClass(){ 
} 

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

, var y, this.y = 15; this.y, obj.y , undefined, , y SomeClass, .

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

+2

y SomeClass. SomeClass, SomeClass, :

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

, , , , . ,

this.x="something"

window.x

+2

, , , y .

, -, , , :

function SomeClass(){
  var y = 15;
}

... , .

, , , , , , y, y .

, :

<script type="text/javascript">
function SomeClass() {
  var y = 15;
  return {
    getY : function() { return y },
    setY : function(newY) { y = newY; }
  };
};

var obj = new SomeClass();

function showY() {
    alert("obj.getY: " + obj.getY()); // alerts current value of y.
}

function updateY() {    
    obj.setY(25);
    alert("updated.");
}

</script>
<input type="button" onclick="showY();return false;" value="showY"/>
<input type="button" onclick="updateY();return false" value="updateY"/>

"showY", "updateY", "showY", .

This is not the only template that I personally use, but javascript is so flexible there are a lot of fun things you can do with it.

I hope I didn’t blow you up too much and hope this helps a bit with the concepts!

+2
source

Source: https://habr.com/ru/post/1758217/


All Articles