The difference between var and let const

This article is derived from 01 One Hour After Work | "JavaScript Enlightenment" reading notes_Amy Li's blog writing code-CSDN blog .

1. An example

I was trying an example while understanding this dynamic binding:

var obj = {
  foo: function () {
    console.log(this.bar) 
  },
  bar: 1
};
var foo1 = obj.foo;
var bar = 2;
obj.foo() // 1
foo1() // 2

What this example wants to express is that this is specified at runtime and points to the object calling the function.

Although the foo1 function is an attribute under the object obj, the global object window executes the foo1 function, so this points to the global object, that is, prints 2.

But executing the foo function under the obj object will print 1, because the object executing the foo function is obj, so this will point to the obj object.

Well, here comes the problem

// 在我将全局的属性
var bar = 2;
// 改为
const bar = 2;
// 或者 
let bar = 2;

Calling the foo1 function again turns out to be undefined.

The reason is: let/constthe defined variables will not be mounted on windowthe object, so the bar attribute cannot be found on the window object.

2. What are the differences between var, let, and const?

1. There is no promotion of variables

2. Temporary dead zone

3. Non-repeatable statement

4. Variables declared by let and const will not be mounted under the window

5. Block-level scope

3. What is the difference between let and const?

1. No matter whether it is in non-strict mode or strict mode, the constant declared by const cannot be reassigned. Constants, as the name suggests, do not change values.

2. When const is declared, it must be initialized and assigned.

Sui Sui Nian, this is a basic interview question, and I have memorized it before, but sure enough, only when I encounter a problem will I be more impressed.

Guess you like

Origin blog.csdn.net/qq_34539486/article/details/127213994