R
R
Rafael™2016-08-15 20:12:27
JavaScript
Rafael™, 2016-08-15 20:12:27

What is the point of creating a variable through var and not by declaring a property of a global object?

first of all, the question is about browser js
, but also about other-other global objects
, here are two options for creating a property / variable:

var адрес = ""
window.адрес = ""

I know about the fact that the difference is in delete / non-delete - but I still don’t understand why I should delete / not delete - this is not a question-problem for me, but I use
a dynamic language, I have never used the ability to delete a property - I can’t understand the code, it’s really it is necessary
for the local scope of functions there is no such question - the var operator is needed there
and vice versa - it is impossible to create a property of the object of the executing function,
but in the global scope, why do I need a non-removable property?
is it possible to state that var is an operator for use in functions
in the global scope it is not required

Answer the question

In order to leave comments, you need to log in

3 answer(s)
D
Dmitry Belyaev, 2016-08-16
@bingo347

Finally in the furnace variables!
For example, let's display the fibonacci element 40 in the console:

[function(){
  this.shift();
  this.push(1, 1);
  for(;this.length <= this[0]; this.push(this[this.length - 1] + this[this.length - 2]));
  console.log(this[this.length - 1]);
}, 40][0]();

S
sugadu, 2016-08-15
@sugadu

in other scopes it is not required.

"other areas" - what are these? There is only the global scope and all the others. Moreover, your application should have at most one variable accessible from the global scope.

V
Vitaly Inchin ☢, 2016-08-16
@In4in

I have made two rules for myself on this topic. I advise you to stick to them too:
1. If we need to read / write a variable to the GLOBAL scope, we specifically use window .
2. If we need to declare a variable in the CURRENT scope, we use var . Even if we are writing in the global now.
This is code culture. Also, this is especially important in those situations when it is planned to include (with the help of assemblers) one js file into another (into an unknown view).
---------
If you are interested in the technical side of two different records, then in theory - accessing variables without "window" should work a little faster.

window.g = 1;
alert(g);
alert(window.g);

Also, when using window, we get naming freedom:
----------------
And I'm silent about ES6, where, in addition to var, things like let and const came. Although, we are talking about globals - therefore, we should only be interested in const.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question