Search code examples
javascriptfunctionobjectlanguage-concepts

How do function-objects fit in the definition of objects in JavaScript?


I've read that an object is a collection of properties and methods. Then if a function is an object, how do function-objects fit in the definition of objects in JavaScript? I'm trying to make an example of a Function with properties and functions but I have any success.

 function myperson(){
    this.name= "Bruno";
    personAbility = function(){document.write(1+1);};
}

document.write(myperson.name);

What am I doing wrong? Can you please help me. Thanks a lot!


Solution

  • You are not creating instance of myperson in your code.

    As you said, functions are objects. Yes, functions are objects and they have properties too. When you are saying myperson.name you are actually accessing the function's name field.

    Since it is a function and it is named function, the name of the function is myperson which you had declared for the function and this is handled by Javascript engine.

    Also, this inside the function points to window object because you are not invoking the function as constructor or binding to any object. So just calling the function will not set myperson.name attribute, you need to use new operator like new myperson and create an object and that object will have the property "name" which you want to access.


    function myperson() {
        this.name= "Bruno";
        this.personAbility = function(){document.write(1+1);};
    }
    
    var per = new myperson();
    document.write(per.otherName);
    //call the personAbility method like below
    per.personAbility();
    

    More about this usage.