Small ambushes in JS variables that you don't know

      Even the front-end great gods are sometimes beaten to the ground by some small ambushes, and immediate prevention is the kingly way. Today Xiaoqian will introduce a few small ambushes in the JS variable settings, and take good care of your small books.

      Variables declared with the var keyword are explicitly declared variables: such as: var abc1 ='hello'

      js allows you to declare variables implicitly without using var: such as: abc2 ='world'

      So, here comes the question, is there any difference between these two variables?

      1. If both abc1 and abc2 are in the global scope, print the window object in the browser console: console.log( window)

      As shown below:

1

      As you can see in the figure above: the global variables abc1 and abc2 are both attributes of the window object, and both have a global scope.

      2. If both abc1 and abc2 are in the function scope, print the window object on the browser console?

2

      As shown below:

3

      As you can see in the above figure: in the function scope, abc1 will not appear in the window object, it is a local variable; and abc2 is still a property of the window object and has a global scope.

      3. If both abc1 and abc2 are in the global scope and are attributes of the window object, can they be deleted like object attributes?

4

      As shown below:

5

      As you can see in the above figure: the variable abc1 declared with var has not been deleted, but is still the property of the window object; the variable abc2 declared without var has been deleted.

      Why is there such a difference?

      This is related to the default object attribute descriptor!

6

      As shown below:

7

      As you can see in the figure above: In the descriptor of the attribute abc1 of the window object, configurable: false means that the attribute cannot be configured or deleted.

8

      As shown below:

9

      As you can see in the figure above: In the descriptor of the abc2 property of the window object, configurable: true means that the property is configurable and can be deleted.

      It is the default setting in the object attribute descriptor that is different, which leads to the difference in whether it can be deleted!

      Variable declarations and function declarations in js will have "declaration promotion". When the js engine parses and executes the code, it is divided into two stages: 1. Pre-parse stage; 2. Line by line execution stage.

      In the pre-analysis stage, the variable abc1 is declared and assigned the initial value undefined; in the line-by-line execution stage, the variable abc1 is assigned the value'hello'; therefore, printing before the variable declaration will not report an error, and the printed value is undefined.

This article is from Qianfeng Education , please indicate the source for reprinting

Guess you like

Origin blog.51cto.com/15128693/2661103