Reputation: 103
I had a question regarding JavaScript Functions. I read Functions as Objects where we can add properties and methods to the functions as well but I notice some strange behavior when I log out the function with the property added. Here is a small example I have taken with object and function.
//Object Example
var obj = {
firstName: 'John',
lastName: 'Doe',
};
obj.address = '111 Main St. New York, NY';
console.log(obj); // Object {firstName: "John", lastName: "Doe", address: "111 Main St. New York, NY"}
//Function Example
function myFunction () {
console.log('Hello World');
}
myFunction.greet = 'Hello JavaScript!';
console.log(myFunction); // function myFunction() { console.log('Hello World');}
As expected the 'greet' property has been added to myFunction but when I log out myFunction I don't the see the property printing out. Why? Where has the property been added? Whereas When I access the property with the dot operator I see the result logging out.
Can someone explain where the property has been added and where it gets stored?
Upvotes: 0
Views: 67
Reputation: 1162
The browser sees that the variable is a function, so when you log out the variable, it tries to print it in the console in a useful way to the developer. Normally we don't look at functions as things that have additional properties, so whatever's implementing console.log doesn't try to show you that information. But the thing you see from console.log isn't really tied to the actual mechanics of the language, it's just there to make things easy to understand for the developer. These properties get stored in the same way, in the same place (RAM) as they do for other objects.
Upvotes: 1
Reputation: 386868
You could get the own properties with Object.keys
of the function.
function myFunction () {
console.log('Hello World');
}
myFunction.greet = 'Hello JavaScript!';
console.log(Object.keys(myFunction));
Upvotes: 1