Access to the properties of functional objects from inside the function body

Functions in javascript are also objects and can have properties. So, is there a way to access my properties from within the function’s own body?

like this

var f = function() { console.log(/*some way to access fa*/); }; fa = 'Test'; f(); //should log 'Test' to console 
+7
javascript function properties
source share
5 answers

arguments.callee is the function itself and is independent of the function name.

 var f = function() { console.log(arguments.callee.a); }; fa = 'Test'; f(); 
+1
source share

You can simply use this:

 console.log(fa); 

If f is executed, f() before fa = 'Test'; you will get undefined in the console since no property is defined with the name / key a . After doing fa = 'Test'; name / key a will be determined by f, and the corresponding value will be 'Test' . Therefore, executing the f function later, the value of 'Test' will be output to the console.

+2
source share

The classic way to do this is to attach the function to itself, after which it can access its own properties through this :

  var f = function() { console.log(this.a); // USE "THIS" TO ACCESS PROPERTY }; fa = 'Test'; f = f.bind(f); // BIND TO SELF f(); // WILL LOG 'Test' TO CONSOLE 
+2
source share

Prototypes is what you are looking for.

 var F = function() { console.log(this.a); } F.prototype.a = 'Test'; // instantiate new Object of class F new F(); 

Hope this helps!

0
source share

You can set this using IIFE:

 var f = (function () { function f () { console.log(fa); } fa = 'Test'; return f; })(); f() // logs 'Test' fa === 'Test' // true 

Note that you do not need to use f (or even a function declaration) to work correctly:

 var f = (function () { var _f = function () { console.log(_f.a); }; _f.a = 'Test' return _f; }); f() // logs 'Test' fa === 'Test' // true 

Some people like to use the same variable to emphasize that inner f will eventually become outer f , and some people prefer to distinguish between each area. In any case, this is normal.

-one
source share

All Articles