私人功能不归还价值

Moz*_*zak 3 javascript

我的代码如下.

var Main = function () {
    var a, b, c, d;
    a = 1;
    b = true;
    c = undefined;

    var _private = function () {
        return 'Function with Private acceess';
    };

    this.getPublic = function () {
        return 'Function with Public access';
    };

    this.getPrivate = function () {
        _private();
    };

};

var o = new Main();
console.log(o.getPublic());
console.log(o.getPrivate());
Run Code Online (Sandbox Code Playgroud)

在上面的代码中,我试图通过public方法访问Main对象o的私有方法getPrivate().但在控制台中的结果是

undefined
Run Code Online (Sandbox Code Playgroud)

为什么_private没有返回所需的值?

Ant*_*ala 7

你忘了这个return说法.请尝试以下方法:

this.getPrivate = function () {
    return _private();
};
Run Code Online (Sandbox Code Playgroud)

如果没有从Javascript函数显式返回值,则认为该函数返回undefined; 不会发出警告.