Mohsin
Mohsin

Reputation: 179

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;

Upvotes: 4

Views: 7788

Answers (2)

Damon
Damon

Reputation: 4336

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)

Upvotes: 0

Pranav C Balan
Pranav C Balan

Reputation: 115212

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)

Upvotes: 1

Related Questions