Javascript关闭。奇怪的行为

时间:2016-04-17 18:26:15

标签: javascript function closures

阅读本文:

http://javascriptissexy.com/understand-javascript-closures-with-ease/

我找到了一些我不了解封口的东西。

这个,例如:

String id = user.get("uid");
entity.addPart("name", new FileBody(id));

返回:

function celebrityName (firstName) {
    var nameIntro = "This celebrity is ";
    // this inner function has access to the outer function's variables, including the parameter​
    function lastName (theLastName) {
        return nameIntro + firstName + " " + theLastName;
    }
    return lastName;
}

var mjName = celebrityName("Michael"); // At this juncture, the celebrityName outer function has returned.​

// The closure (lastName) is called here after the outer function has returned above​
// ​// Yet, the closure still has access to the outer function's variables and parameter​

console.log(mjName("Jackson")); // This celebrity is Michael Jackson
console.log(mjName);
mjName("test");

但我不明白为什么如果我添加另一个封闭:

This celebrity is Michael Jackson
[Function: lastName]

我得到了这个结果:

function celebrityName (firstName) {
    var nameIntro = "This celebrity is ";
    // this inner function has access to the outer function's variables, including the parameter​
    function lastName (theLastName) {
        return nameIntro + firstName + " " + theLastName;
    }
    function firstNameFunc (theLastName) {
        return nameIntro + theLastName + " " + firstName;
    }
    return lastName;
}

var mjName = celebrityName("Michael"); // At this juncture, the celebrityName outer function has returned.​

// The closure (lastName) is called here after the outer function has returned above​
// ​// Yet, the closure still has access to the outer function's variables and parameter​

console.log(mjName("Jackson")); // This celebrity is Michael Jackson
console.log(mjName);
mjName("test");

为什么会这样?我理解该调用返回闭包,因为它的值存储在变量中,但在第二种情况下它只返回第一个闭包。

非常感谢你!

0 个答案:

没有答案
相关问题