I am new to Javascript. I did a course sometime back and I am trying to remember a concept about that all the functions are objects that will contain a property that will contain the code written inside that function and another property that contains name of the function.
I tried that and I found name property like below. but not able to find the code property. Does that really exist or I may be wrong.
console.log(
(function f() {
a = 1
}.name)
)
so the property should return
a=1
Not trying to do anything. I am brushing up my JS as I want to learn angular.
3 Answers 3
but not able to find the code property. Does that really exist or I may be wrong.
It exists conceptually, but it is an internal property, which cannot be accessed from user code. It's called [[ECMAScriptCode]]. See the spec for more details.
In reality though, browsers could implement functions in any way they want, as long as they behave as described in the spec.
What you can do in user code is call the function's toString method. That will return a string representation of the function itself, though the exact representation is implementation dependent.
1 Comment
I believe you are looking for something like the following:
function f(){
console.log("a = 1");
};
console.log(f.toSource());
console.log(f.toString());
https://jsfiddle.net/agraymd/ar5hgkv8/1/
.toSource is however not a standard feature. From the MDN:
This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.
function.toSring(); seems to be a better alternative, which is a standard feature. More on that here:
1 Comment
Try f.toString() where f is the function you wish to obtain the source code of.
({a:1}).a?