Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do javascript functions have properties in them?

function myFunc(){
    console.log(myFunc.message);
}
myFunc.message = "Hi John";

myFunc();

Executing the above results in -

Answer: 'Hi John'

How is the function myFunc have the property message on it? typeof myFunc results in "function" and console.log(myFunc) displays the function content (without the property message on it).

How does the above work? Is a function in JavaScript internally an object?

Note - I am aware that functions have other parameters like prototype and length on them. But I am not sure how these are implemented as well.

Additional query - Since console.log(myFunc) does not show the object properties, how do I list all the properties of a function object?

like image 823
Nithin Kumar Biliya Avatar asked Oct 19 '25 02:10

Nithin Kumar Biliya


1 Answers

How does the above work? Is function in javascript internally an object?

Yes

function example() {};

console.log(example instanceof Object);
like image 167
Quentin Avatar answered Oct 21 '25 15:10

Quentin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!