Dig deep into the relationship between Javascript global object properties and variable declarations

About global object and variable declaration

Today I reviewed the js learning video. When I talked about the constructor, I added the this point of the constructor and the ordinary function, which talked about the window object.

We all know that the this of the constructor points to the instantiated object, while the this of the ordinary function actually points to the window object. So there will be this situation:

function f1(){
    
    
    console.log(this);   
}
f1();     //这里调用后打印出来的会是window对象

Functions such as alert are actually members of the window global object, and window can be omitted:

alert('123');
window.alert('123');   //这两个是等同的

The variables we declare will actually become properties of the window object:

let num = 100;
console.log(window);   
//-> 会发现window对象里会多出一个属性num,值为100

Think of the sentence: "Everything in JS is an object". It suddenly occurred to me that this kind of variable declaration is actually adding attributes to the window object? Are the two equivalent? In other words:

** global scope window.numand var numis not the same? **

With this idea, I did the next test:

//测试直接给window添加属性,能不能向变量一样仅凭属性名就打印?
window.num = 10;
alert(num);    //-> 10
//果然,测试的结果是,num可以正常打印

//那再使用变量重新声明呢?
window.age = 18;
var age = 20;    
alert(age);   //-> 20
//果然,打印出来的是重新声明的值,这是不是意味着window.age这个属性被变量声明给“覆盖”了呢?
alert(window.age);  //-> 20
//说明确实被覆盖了

//反过来也一样
var name = 'Jack';
window.name = 'Nick';
alert(window.name);   //-> Nick
//一次性打印两个时
console.log(window.name,name);  //-> Jack Jack

//看看两者是否相等:
console.log(window.name===name);   //-> true

Then I flipped through the book "JavaScript Advanced Programming", there is a passage in the window object:

Because the window object is reused as the Global object of ECMAScript, all global variables and functions declared by var will become the properties and methods of the window object. such as:

var age = 29;
var sayAge = () => alert(this.age);

alert(window.age);  // 29
sayAge();   // 29
window.sayAge();  //29

There is also this paragraph:

But using let or const instead of var will not add the variable to the global object.

In other words, this situation will occur:

window.age = 18;
let age = 20;    
console.log(age , window.age);   //-> 20 18   
//两个都可以正常打印,值互不干扰

const num = 10;
console.log(window.num);   //-> undefined

In addition, access to undeclared variables will throw an error, but you can query on the window object for possible undeclared variables:

var newVal = oldval;  //会抛出错误,因为oldVal没有声明

var newValue = window.oldvalue;
//这里不会抛出错误,因为这里是属性查询
//newValue会被设置成undefined

Guess you like

Origin blog.csdn.net/Lu_xiuyuan/article/details/112987642