Вопрос

I'm having a problem understanding why name is getting a value here

(function() {
  (function() {
    var name = 'Fido';
  })();
})();

console.log(name + ' says woof'); //Output: Fido says woof

Shouldn't the variable name be local to the internal function?

Это было полезно?

Решение

The variable is local, and the value that you see doesn't come from the assignment inside the function.

You have named your window "Fido" also, and when you use name in the global scope, you get the window.name property.

If you try it in a jsfiddle, you will get "result says woof".

Demo: http://jsfiddle.net/Guffa/eDxf3/

Другие советы

You are wrong! If executed in browser console this code will output: says woof

I think you need to understand hoisting better. This article is definitely going to help you. Here is a short description taken from the article:


In JavaScript, a name enters a scope in one of four basic ways:

  • Language-defined: All scopes are, by default, given the names this and arguments.
  • Formal parameters: Functions can have named formal parameters, which are scoped to the body of that function.
  • Function declarations: These are of the form function foo() {}.
  • Variable declarations: These take the form var foo;.

Function declarations and variable declarations are always moved (“hoisted”) invisibly to the top of their containing scope by the JavaScript interpreter. Function parameters and language-defined names are, obviously, already there. This means that code like this:

function foo() {
    bar();
    var x = 1;
}

is actually interpreted like this:

function foo() {
    var x;
    bar();
    x = 1;
}

It turns out that it doesn’t matter whether the line that contains the declaration would ever be executed. The following two functions are equivalent:

function foo() {
    if (false) {
        var x = 1;
    }
    return;
    var y = 1;
}

function foo() {
    var x, y;
    if (false) {
        x = 1;
    }
    return;
    y = 1;
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top