简体   繁体   English

使用JavaScript私有方法:

[英]Working with JavaScript private methods:

I am following Douglas Crockford's tutorial on the visibility of JavaScript variables and functions here : http://javascript.crockford.com/private.html 我在这里关注Douglas Crockford关于JavaScript变量和函数的可见性的教程: http : //javascript.crockford.com/private.html

I have written the following MyClass.js file and I am running it from the terminal using node. 我已经编写了以下MyClass.js文件,并且正在使用node从终端运行它。 Below I show my output on the terminal and my class. 下面,我在终端和班级上显示我的输出。 I do not understand why I get returned an "undefined" (instead of just true) and also, why my console.log(log) is not showing anywhere? 我不明白为什么我会返回“未定义”(而不是真实的),并且为什么我的console.log(log)没有显示在任何地方?

$ node MyClass.js 
undefined
true

And my class 还有我的课

function MyClass(log) 
{
    this.log = log;
        var that = this; 
        function _evaluate (log)
        {
             console.log(log);
             return true;
        };

    this.evaluate = function() 
    {
    return _evaluate() ? true : false;
    };

}

 var myObject = new MyClass('this is a test');
 console.log(myObject.evaluate());

You call _evaluate with no arguments, so it prints undefined once (line 7), then true (line 19). 您不带任何参数调用_evaluate ,因此它先输出一次undefined (第7行),然后输出true (第19行)。

Finally it prints undefined because your script as a whole has no return value. 最后,它打印undefined因为您的脚本作为一个整体没有返回值。

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

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