JS Tutorials
JS Objects
JS Functions
JS Classes
JS Async
const
person = {
firstName: "John",
lastName: "Doe",
id: 5566,
fullName: function() {
return this.firstName + " " +
this.lastName;
}
};
In a function definition, this
refers to the "owner" of the
function.
In the example above, this
is the person
object that "owns" the
fullName function.
In other words, this.firstName means the firstName property of this object.
JavaScript methods are actions that can be performed on objects.
A JavaScript method is a property containing a function definition.
Property | Value |
---|---|
firstName | John |
lastName | Doe |
age | 50 |
eyeColor | blue |
fullName | function() {return this.firstName + " " + this.lastName;} |
Methods are functions stored as object properties.
You access an object method with the following syntax:
objectName.methodName()
You will typically describe fullName() as a method of the person object, and fullName as a property.
The fullName property will execute (as a function) when it is invoked with ().
This example accesses the fullName() method of a person object:
name = person.fullName();
If you access the fullName property, without (), it will return the function definition:
name = person.fullName;