Answer the question
In order to leave comments, you need to log in
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:
this.k = {myObj:'ok'};
var k;
k = {}; // this.k == {} => this.k и var k суть одно и то же,
// когда находимся внутри глобального объекта (this === global)
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
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
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)
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.
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 questionAsk a Question
731 491 924 answers to any question