且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

函数内部的return语句有什么用?

更新时间:2022-12-28 21:34:03

在最基本的层面上, return 关键字定义了函数应返回的内容。所以如果我有这个功能:

On the most basic level, the return keyword defines what a function should return. So if I have this function:

function foo() { return 4; }

然后调用它:

var bar = foo();

foo()将返回 4 ,因此现在 bar 的值也是 4

foo() will return 4, hence now the value of bar is also 4.

根据您的具体示例:

在此用例中,返回用于基本上限制对哈希变量内部变量的外部访问。

In this use case the return is used to basically limit outside access to variables inside the hash variable.

任何写成的函数如下:

Any function written like so:

(function() {...})();

是自我调用,这意味着它会立即运行。通过将 hash 的值设置为自调用函数,这意味着代码可以尽快运行。

Is self-invoking, which means it runs immediately. By setting the value of hash to a self-invoking function, it means that code gets run as soon as it can.

该函数然后返回以下内容:

That function then returns the following:

return {         
    contains: function(key) {
        return keys[key] === true;         
    },
    add: function(key) { 
        if (keys[key] !== true){
            keys[key] = true;             
        }
    }     
};

这意味着我们可以访问包含添加函数如下:

This means we have access to both the contains and add function like so:

hash.contains(key);
hash.add(key);

哈希里面,还有一个变量 keys 但是 hash 设置为自调用函数不返回,因此我们无法访问 key 哈希之外,所以这不起作用:

Inside hash, there is also a variable keys but this is not returned by the self-invoking function that hash is set to, hence we cannot access key outside of hash, so this wouldn't work:

hash.keys //would give undefined

它本质上是一个构造代码的方法,可以通过使用JavaScript闭包来创建私有变量。有关详细信息,请查看此帖子: http://net.tutsplus.com/tutorials/javascript-ajax/quick-tip-private-variables-in-javascript/

It's essentially a way of structuring code that can be used to create private variables through the use of JavaScript closures. Have a look at this post for more information: http://net.tutsplus.com/tutorials/javascript-ajax/quick-tip-private-variables-in-javascript/

希望这有助于:)

杰克。