javascript - Can I use function as an object inside the same function -
i write code follows,
function myfunction(){ myfunction.myvar = "somevar"; }
after execute function, can able access myfunction.myvar
how working? , if so, problem hidden in this?
if problem, please explain context of that.
how working?
when declare function in execution context, binding added variable environment of context. when reference identifier, current variable environment checked see if binding exists identifier.
if no binding exists, outer variable environment checked, , on, global scope.
so:
// outer scope // binding exists 'example' function example() { // inner scope // no binding 'example' // references 'example' in outer scope example.x = 1; }
what problem hidden in this?
there none (in general... although whether it's right solution depends on you're trying do).
you creating "static" property of function. javascript functions first-class can set properties on them other object.
note behaviour different if have named function expression, rather function declaration:
var x = function example () { // identifier 'example' in scope in here };
Comments
Post a Comment