JS basis - Scope

Scoping issues

The following code prints what, and why?

// 情况 1 

//  情况 2
var b = 10;
var c = function b() {
  b = 20;
  console.log(b)
}
c()

// 上面两种都打印:
ƒ b() {
  b = 20;
  console.log(b)
}

b function (function expressions defined functions) is equivalent to using a constant const definitions inside can not be reassigned, if in strict mode, will get an error "Uncaught TypeError: Assignment to constant variable."

The following simple transformation code, so that the printing 10 and 20, respectively

var b = 10;
(function b() {
  b = 20;
  console.log(b)
})()

Print 10:

var b = 10;
(function b(b) {
  window.b = 20;
  console.log(b)
})(b)
var b = 10;
(function b() {
  b.b = 20;
  console.log(b)
})()

Print 20:

var b = 10;
(function b(b) {
  b = 20;
  console.log(b)
})()
var b = 10;
(function b() {
  var b = 20;
  console.log(b)
})()

Here's what the code output

var a = 10;
(function () {
    console.log(a)
    a = 5
    console.log(window.a)
    var a = 20;
    console.log(a)
})()

Sequentially outputs: undefined -> 10 -> 20

Resolution:

In the immediate execution function, var a = 20; statement defines a local variable a, since js variable declarations lifting mechanism , the local variable a declaration will be raised to immediately execute the top body of a function, and due to the lifting does not include the assignment, so the first print statement will print undefined, the last statement will print 20.

Since global var will be mounted to the next window object, and there are variable functions performed immediately prompts.
'a = 5;' This statement is executed, a local variable has been declared, so the effect it produces is to assign a local variable, then the beginning window.a still assigned 10

var variable definition upgrade

var name = 'Tom';
(function() {
if (typeof name == 'undefined') {
  var name = 'Jack';
  console.log('Goodbye ' + name);
} else {
  console.log('Hello ' + name);
}
})();

Output: 'Goodbye Jack'

Guess you like

Origin www.cnblogs.com/nayek/p/11729939.html