简体   繁体   English

为什么函数没有被调用并抛出错误?

[英]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. 当我执行它时,警报语句完美地打印了printName函数,但是函数调用name()给出错误,指出字符串不是函数。 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. 我试图在这里理解闭包,并尝试这样做,并与js中的范围管理相混淆。

You haven't declared name in the outer scope, so it's using the global scope, and is actually pointing to window.name . 您尚未在外部范围中声明name ,因此它正在使用全局范围,并且实际上指向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() . 由于window.name是窗口的名称,因此当您为其分配窗口时,它会将字符串内容分配给窗口的名称,并且仍然是字符串-这就是为什么您不能使用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. 请注意,这仅在此代码本身在另一个范围内时才有效-如果它在全局范围内,即使使用var name也无济于事,因为它仍会与global window.name属性冲突。

That is because inside callName() you set the var name to string. 这是因为在callName()您将var name设置为string。 If you do this: 如果您这样做:

var name = callName();

You will be creating a new var name different of the one inside callName() . 您将创建一个与callName()内部不同的新var name

Fiddle 小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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