Function call to declare object property in JavaScript -
is possible use function call set object property in js? tried didn't work.
var name = "richard"; function showname() { var name = "jack"; // local variable; accessible in showname function console.log(name); // jack } console.log(name); // richard: global variable var myobj = { name: showname(); }; console.log(myobj.name);
is possible use function call set object property in js?
yes, right-hand side of property initializer can contain expression, including function call. expression evaluated , resulting value assigned property. (and if have multiple property initializers in object initializer, they're executed in source-code order.)
your example didn't work because didn't return name
showname
(and because has ;
):
var name = "richard"; function showname() { var name = "jack"; snippet.log(name); return name; // <== added return name; } snippet.log(name); var myobj = { name: showname() // <== removed ; }; snippet.log(myobj.name);
<!-- script provides `snippet` object, see http://meta.stackexchange.com/a/242144/134069 --> <script src="//tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
Comments
Post a Comment