+ 1

Help me with explanation of code

I have function function foo() { return 20.1;} foo.bar = " What is bar, what is foo in this case?!?!"; alert(typeof(foo.bar)); if 'foo' is a reference on the function(i check i print foo and engine show me the functtion description) what is the bar?!?!?!?

16th May 2020, 8:43 PM
george
george - avatar
3 Respuestas
+ 2
george It's mainly used for backward compatibility and functional programming. It could be useful in other situations too but I can't be sure without browsing a bit. It's used seldom and other approaches are usually preferred but you should know that it's possible, and remember that often functions behave like any other object would do.
16th May 2020, 10:50 PM
Kevin ★
+ 5
Foo is referencing your function, yes. Functions in Javascript are objects too and as such they accept new properties(key-value pairs). Adding a property to a function object that way is not very common but it can be useful in certain situations. For example before the introduction of the "static" keyword for "classes" the foo.bar form was the way to mimic the functionality of static fields in constructor functions.
16th May 2020, 9:09 PM
Kevin ★
+ 2
Ou thanks, so now such representation is not used?! or used very very very seldom
16th May 2020, 9:20 PM
george
george - avatar