我正在研究这段代码

var myModule = function () {


    //"private" variables:
    var myPrivateVar = "01I can be accessed only from within YAHOO.myProject.myModule.";

    //"private" method:
    var myPrivateMethod = function () {
        console.log("02I can be accessed only from within YAHOO.myProject.myModule");
    }


    return  {
        myPublicProperty: "I'm accessible as YAHOO.myProject.myModule.myPublicProperty.",
        myPublicMethod: function () {
            console.log("1I'm accessible as YAHOO.myProject.myModule.myPublicMethod.");

            //Within myProject, I can access "private" vars and methods:
            console.log("2"+myPrivateVar);
            console.log("3"+myPrivateMethod());

            //The native scope of myPublicMethod is myProject; we can
            //access public members using "this":
            console.log("4"+this.myPublicProperty);
        }
    };

}();


想知道输出:

1I'm accessible as YAHOO.myProject.myModule.myPublicMethod.
201I can be accessed only from within YAHOO.myProject.myModule.
02I can be accessed only from within YAHOO.myProject.myModule
3undefined
4I'm accessible as YAHOO.myProject.myModule.myPublicProperty.


谁能解释为什么如果myPrivateMethod()如输出中所示未定义,则只能从YAHOO.myProject.myModule中访问02I?为何在console.log("3"+myPrivateMethod())之前显示它?

最佳答案

谁能解释为什么如果myPrivateMethod()未定义(如输出所示),则只能从YAHOO.myProject.myModule中访问02I吗?


myPrivateMethod不是undefinedmyPrivateMethod()是。该函数已定义,没有return语句,因此其返回值为undefined


  以及为什么在console.log(“ 3” + myPrivateMethod())之前显示它?


在将myPrivateMethod()与字符串console.log连接并传递给另一个"3"之前,先对其进行评估(以便执行该函数并触发其中的console.log语句)。

关于javascript - 为什么实际上从Javascript闭包调用了未定义的函数?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31702291/

10-10 05:35