简体   繁体   中英

How to assign a return value from a function directly to an object literal

I have the following code:

"myFunction" is an anonymous function that I have got as a parameter. ...

newObj = { id: idValue, div: null };
newObj.div = myFunction();

Is there a shorter way, a way to directly assign the result of a function to the object literal, something like:

newObj = { id: idValue, div: (myFunction ())};

Thanks alot in advance Wolfgang

what you have should work:

newObj = {id:idValue, div: myfunction()};

JavaScript is a functional programming, which means that you can use anonymous functions almost everywhere. Consider this example:

var human = { firstName: 'Saeed', lastName: 'Neamati', getName: function () {
        return this.firstName + ' ' + this.lastName;
    }
};
human.getName();

Here, an anonymous function is assigned to the getName attribute. Now, in your example, two things are possible.

  1. If you want to assign the returned value of the function to an attribute of the object (as you specified), then you should use:

    newObj = {id:idValue, div: myfunction()};

  2. If you want to assign the function , not the returned value of the function to the attribute, then you should drop parantheses:

    newObj = {id:idValue, div: myfunction};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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