简体   繁体   中英

why is the the function not getting called and throwing me an error?

The below is my code

function callName() {
    var name="x";

    function printName(){
        alert(name);
    }

    return printName;
}

name = callName();
alert(name);
name();

When i execute it, the alert statement is printing the printName function perfectly, but the function call name() is giving an error stating string is not a function. if scope is the problem the alert should have printed the name instead of the function. I am trying to understand closures here and was trying this out and got confused with the scope management in js.

You haven't declared name in the outer scope, so it's using the global scope, and is actually pointing to window.name . Just declare it as a local variable, and you're set:

function callName() {
    var name="x";

    function printName(){
        alert(name);
    }

    return printName;
}

var name = callName();
alert(name);
name();

Since window.name is the name of the window, when you assign to it, it's assigning the string contents to the name of the window, and is still a string - that's why you can't call it with name() .

Note that this will only work if this code itself is within another scope - if it's on the global scope, even using var name won't help, as it will still conflict with the global window.name property.

That is because inside callName() you set the var name to string. If you do this:

var name = callName();

You will be creating a new var name different of the one inside callName() .

Fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM