0

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.

asked Apr 6, 2016 at 4:39
2

3 Answers 3

4

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.

answered Apr 6, 2016 at 4:43
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks great link to the spec!
2

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:

.toString();

answered Apr 6, 2016 at 4:48

1 Comment

Yes tosource seems only for gecko engines
0

Try f.toString() where f is the function you wish to obtain the source code of.

answered Apr 6, 2016 at 4:44

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.