G
G
Garegin Kazaryan2016-11-15 17:53:55
JavaScript
Garegin Kazaryan, 2016-11-15 17:53:55

Is the behavior of variables in the scope of a global object different from the behavior in created objects?

Question from the category of sports interest. Tested in Node.
Essence:

  • in the scope of the global object:
this.k = {myObj:'ok'};
var k;
k = {};  // this.k == {}  => this.k и var k суть одно и то же,
         // когда находимся внутри глобального объекта (this === global)

  • and now the same in the scope of any other object that we create from the function:
var MyObj = function(){
this.k = {myObj:'ok'};
var k;
k = {}; 
console.log(k, this.k);
}
var obj = new MyObj(); // this.k == {myObj:'ok'} => this.k и var k
                       // суть разные ячейки, когда находимся внутри созданного нами объекта obj

Why such different behavior? Why, in the global scope, all variables "stick" to the global object as its properties, but inside our object, var k does not behave like this (the variable k is not a property (this.k = undefined) even when we are inside the function during its execution, here:
var z = function(){
var k; 
k ={n:'no'};
console.log(this.k);
}
var t = new z(); // => undefined undefined

Answer the question

In order to leave comments, you need to log in

3 answer(s)
G
Garegin Kazaryan, 2016-11-15
@garka

I dug another question and found a very good analysis on the stack:
stackoverflow.com/questions/4862193/difference-bet...
in short - the variables from the new standard (set via let, const) behave decently, and the old variants stick to the global object as properties (0_o)

A
Aves, 2016-11-15
@Aves

The behavior is different because the execution contexts are different. If you want to squeak your brains, you can read the specification www.ecma-international.org/ecma-262/7.0/#sec-execu... or articles on dmitrysoshnikov.com/category/ecmascript
By the way, variables declared in the global context via let and const are not written to the properties of the global object.

K
Konstantin Kitmanov, 2016-11-15
@k12th

Why, the birth trauma of JavaScript - Brendan Eich thought this would be a wonderful idea for a scripting language. And now it’s too late to change, you can’t take and break half of the sites on the Internet.
You should know this, but you should not use it, and it is better to minimize the number of variables added to the global scope.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question