Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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(_);
like image 261
user6920839 Avatar asked Jun 22 '26 15:06

user6920839


1 Answers

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.

like image 118
James Donnelly Avatar answered Jun 24 '26 07:06

James Donnelly



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!