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.
精彩评论