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!
3 Answers 3
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.
4 Comments
per.personAbility() function.You're doing it right, you just need to instantiate your myperson object. You can do this by writing var myPerson = new myperson(). Then, console.log(myPerson) should display:
myperson {name: "Bruno"}
To go along with your document.write example, you could do document.write(myPerson.name).
Comments
The this keyword will become available once you treat your function as a constructor function, meaning that you have to create a new instace by using the new keyword:
function myperson(){
this.name= "Bruno";
personAbility = function(){document.write(1+1);};
}
var person = new myperson();
document.write(person.name);
Comments
Explore related questions
See similar questions with these tags.
thisnot refering to themypersonfunction (and you never executing that code), have a look at Why can't I set a JavaScript function's name property?