JavaScript new keyword and object areas

Later today I scrolled through ejhon.com slides and I found out the following:

Give this code

function katana () {
this.myvar = true;
}
katana ();
console.info (myvar);

At that moment when I compiled the code, I thought that myvar was attached to the katana function. In fact, it binds to window objects that pollute the global namespace.

I went back to my projects that use the same approach .. a little different

function katana () {
this.myvar = true;
}
var xyz = new katana();
console.info (myvar);

I have a function object, and instead of executing the function, I just create a new instance (I'm not quite sure what is going on). Then I use xyz to store the values ​​and use these values ​​through prototyped methods to do some tasks.

What surprised me when I debugged with FireBug is that xyz does not exist. There are no variables for the window object. Why?

, xyz window > , DOM . - , node, "scopechain" , xyz.

, ? , , ? , , .

+3
1

new katana(), Javascript katana this. , , ( katana , ) , 'prototype' (, ..) katana.

, , . new katana(), Javascript katana katana . katana(), this - , . ( x.foo, this == x.) , , this window.

, xyz , var. . , window.xyz.

+3

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


All Articles