Search code examples
javascriptfunctionobjectjavascript-objectsfunction-object

JavaScript Functions as Objects


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?


Solution

  • 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));