user6920839 user6920839 - 1 month ago 7
Javascript Question

how to access object property from inside function in javascript, is it possible?

I have a function and an object inside that function. I am returning the object. How can I call the function and then get the

obj.a
in
console.log();
?



function _() {
var obj = {};

obj.a = "one";
obj.b = "two";

return obj;
}

console.log(_);




Answer

Simply execute the function (_(), which will return an object), then access its inner properties using dot notation as you normally would:

function _() {
  var obj = {};

  obj.a = "one";
  obj.b = "two";

  return obj;
}

console.log(_().a);
console.log(_().b);

You may want to consider storing the result of executing the function as a separate variable first though, rather than executing it repeatedly every time you wish to access a property from the object it returns.

Comments