简体   繁体   中英

how to create object inside function of value in javascript

How can I create and access object inside anonymous function of value?

var obj1 = {key1: "val1", key2: {a: "this is a val"} };

in obj1 I know I can access it as console.log(obj1.key2.a);

Is it possible to do it this way

var obj2 = {key1: "val1", key2: function(){   {a: "this is a val"}   }};

If it is then how I will access the a: val;

You need to return the object from the function in order to access it. After adding return statement you can get the object by calling the function then get the property a .

 var obj2 = { key1: "val1", key2: function() { return { a: "this is a val" } } }; console.log(obj2.key2().a) 

If you want a bit more flexibility (and to be able to access your value the way you originally proposed), you can have key2 be a getter function instead of a regular key pointing to a function:

 var obj2 = { key1: "val1", get key2 () { return { a: "this is a val" } } }; console.log(obj2.key2.a) 

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