Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get function object property from within function

Tags:

javascript

In JavaScript, functions can have properties. Like this:

var f = function(){ console.log("Hello!"); }
f.x = "Whoohoo";

How do I retrieve x from code within f() that might be called long after the variable f goes out of scope?

like image 879
Seva Alekseyev Avatar asked May 06 '26 05:05

Seva Alekseyev


1 Answers

You could use the property accessor, like the assignment.

var f = function() { console.log("Hello! " + f.x); }
f.x = "Whoohoo";

console.log(f.x);
f();

For stable access, you could use a named function

var f = function foo() { console.log("Hello! " + foo.x); }
//               ^^^ >>>>>>>>>>>>>>>>>>>>>>>>>>> ^^^
f.x = "Whoohoo";

console.log(f.x);
f();
like image 136
Nina Scholz Avatar answered May 08 '26 19:05

Nina Scholz



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!