开发者

Assign an anonymous return value directly to a property of an object

开发者 https://www.devze.com 2023-02-10 10:52 出处:网络
How can I assign the returned value of an anonymous function to a property of my JSON object? Here\'s my scenario:

How can I assign the returned value of an anonymous function to a property of my JSON object?

Here's my scenario:

            selectOptionData.push({
                value: 123,
                text: 'Hi there',
                selected: false,
开发者_StackOverflow                transportObject: function(){
                    var transObj = null;
                    $.each(transports, function(i, t)
                    {
                        if (t.ID == currentTranspObjID) {
                            transObj = t;
                            return;
                        }
                    });

                    return transObj;
                }
            });


First: You don't have a JSON object. You have a normal JavaScript object defined with object literal notation.

I assume you want to execute the anonymous function immediately? Just add () after its body:

transportObject: (function(){
    var transObj = null;
    $.each(transports, function(i, t)
    {
        if (t.ID == currentTranspObjID) {
            transObj = t;
            return;
        }
     });
    return transObj;
}())  // <- see here

This is also called immediate function as you define and immediately execute it.


If I understand your question correctly, you can do the following:

var myObject = {
    value: 123,
    text: "hi there",
    magics: (function () {
      // Do things.
      return "stuff";
    }())
};

Wrapping the function in parentheses lets you call the function in-line.

0

精彩评论

暂无评论...
验证码 换一张
取 消