简体   繁体   English

在Javascript函数中返回值

[英]Returning Values in Javascript Functions

I came across this answer while understanding closures by @Jacob Swartwood https://stackoverflow.com/a/6472397/3179569 我通过@Jacob Swartwood了解关闭时遇到了这个答案https://stackoverflow.com/a/6472397/3179569

and I could not understand how littleGirl called story as if it was a function. 而我无法理解littleGirl如何称故事就好像它是一个功能。 Shouldn't it have been littleGirl(); 不应该是littleGirl(); so that the princess function was called? 这样princess功能被称为? Also isn't the princess function returning a key value pair, which means it's returning an object? 同样不是返回键值对的公主函数,这意味着它返回一个对象? So how can littleGirl access a key as if it was a function? 那么littleGirl如何才能访问密钥,就好像它是一个函数一样? (because story is a key right?) (因为story是关键的吗?)

I tried searching for the term returning a key value pair in javascript but didn't come up with a decent explanation. 我尝试在javascript中搜索返回键值对的术语,但没有得到一个像样的解释。 I'm hoping someone here can help me. 我希望有人可以帮助我。 I come with a background in Java and C++ so this is a bit confusing. 我有Java和C ++的背景,所以这有点令人困惑。

function princess() {


    var adventures = [];

    function princeCharming() { /* ... */ }

    var unicorn = { /* ... */ },
        dragons = [ /* ... */ ],
        squirrel = "Hello!";


    return {


        story: function() {
            return adventures[adventures.length - 1];
        }
    };
}


var littleGirl = princess();

littleGirl.story();

Maybe if we break it down and add one thing at a time it will make more sense. 也许如果我们将其分解并一次添加一件事情就会更有意义。

First, a function princess that returns undefined : 首先,返回undefined的函数princess

function princess() {
}

princess();

//> undefined

Next, a function that returns an object literal: 接下来,返回一个对象文字的函数:

function princess() {
    return {};
}

princess();

//> Object {}

Next, a function that returns an object literal with a function inside it (which returns undefined ): 接下来,返回一个带有函数的对象文字的函数(返回undefined ):

function princess() {
    return {
        story: function {}
    };
}

princess().story();

//> undefined

Next, a function that returns an object literal with a function inside that returns an array: 接下来,返回一个带有函数的对象文字的函数返回一个数组:

function princess() {
    return {
        story: function {
            return [];
        }
    };
}

princess().story();

//> Array []

I think that covers most of your points. 我认为这涵盖了你的大多数观点。 However, none of this has much to do with closures. 但是,这些都与闭包无关。 In your example, the array adventures is what is being closed over. 在您的示例中,阵列adventures是被关闭的。 This allows kind of a private member (like with access modifier in Java). 这允许一种private成员(如Java中的访问修饰符)。

So, finally, a function that returns an object literal with a function inside which closes over a private array: 所以,最后,一个函数返回一个具有函数的对象文字,其中的函数关闭私有数组:

function princess() {
    var myArray = [1, 2, 3];
    return {
        story: function {
            return myArray[myArray.length - 1];  // get the last one: 3
        }
    };
}

princess().story();

//> 3

To expand on what @asantaballa said, story is a key with a value of function () {...} . 为了扩展@asantaballa所说的, story是一个具有function () {...}值的键。 If you were to run console.log(littleGirl.story) you would see function princess/<.story() 如果您要运行console.log(littleGirl.story)您会看到function princess/<.story() console.log(littleGirl.story) function princess/<.story()

Princess could be rewritten like this... 公主可以像这样改写......

function princess() {


    var adventures = [];

    function princeCharming() { /* ... */ }

    var unicorn = { /* ... */ },
        dragons = [ /* ... */ ],
        squirrel = "Hello!";

    var getAdventure = function () {
        return adventures[adventures.length - 1];
    };

    var retObj = new Object(); // same as '{}'
    retObj.story = getAdventure;

    return retObj;
}


var littleGirl = princess();

littleGirl.story();

Or in another way, princess is just a function. 或者换句话说,公主只是一种功能。

You call it with princess() and it returns something. 你用princess()调用它并返回一些东西。

That something it returns, is an object like this: 它返回的东西是这样一个对象:

{
    story:function() {...}
}

This object has a function (story) inside. 这个对象里面有一个函数(故事)。

A function is, after all, just some data you can pass around and assign to variables like any other data. 毕竟, 函数只是一些可以传递的数据,并像其他任何数据一样分配给变量。

An object is a way of grouping different data together into a single.. well.., object 对象是一种将不同数据组合在一起成为一个..井,对象的方法

So you can put functions inside objects. 所以你可以把函数放在对象中。 And functions can return any data kind, including objects. 函数可以返回任何数据类型,包括对象。

// set variable aFunc to some function
var aFunc=function() {...}

// call it
aFunc();

// Set an object
var anObj= {
    anInt:3,
    aString:"blabla",
    itsFunction:aFunc
}

Call the function inside it 调用里面的函数

anObj.itsFunction();

A function returning the same object is 返回同一对象的函数是

function getAnObj() {
    return {
        anInt:3,
        aString:"blabla",
        itsFunction:aFunc
    }
}

In our case, princess is just like getAnObj, story is just like aFunction 在我们的例子中,公主就像getAnObj,故事就像一个功能

So 所以

princess().story();

is just like 就像

var anObj=getAnObj();
anObj.itsFunction();

A function ( princess ) returned an object ( littleGirl ) that has a function inside it ( story ). 函数( princess )返回一个对象( littleGirl ),里面有一个函数( story )。 And you call it. 你打电话给它。

A function ( getAnObj ) returned an object ( anObj ) that has a function inside it ( itsFunction ). 函数( getAnObj )返回一个对象( anObj ),其中包含一个函数( itsFunction )。 And you call it. 你打电话给它。

Names.. 名称..

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

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