JavaScript Object Methods
A method is a function stored in a property. A method runs when a call names its object and its property.
Read through this
A method is a function stored in a property, and fullName is one here. The method builds a full name from the name property.
const person = {
name: "Ana",
age: 9,
fullName: function () {
return this.name + " Berg";
}
};
console.log(person.fullName());Change through this
The birthday method adds 1 to the age property. The line after the call logs the new age.
const person = {
name: "Ana",
age: 9,
birthday: function () {
this.age = this.age + 1;
}
};
person.birthday();
console.log(person.age);List the keys
Object.keys returns the property names of an object. The result logs as a compact list here.
const person = { name: "Ana", age: 9, city: "Oslo" };
console.log(Object.keys(person));Example
const person = {
name: "Ana",
age: 9,
fullName: function () {
return this.name + " Berg";
},
birthday: function () {
this.age = this.age + 1;
}
};
console.log(person.fullName());
person.birthday();
console.log(person.age);
console.log(Object.keys(person));Key points
- this: the object before the dot in a call such as person.fullName()
- Keys are the property names of an object.
- A method call ends with parentheses, such as person.birthday().
- A method can read the properties of its own object through this.
- A method can also change a property of its own object through this.
In this example, the person object holds two data properties and two methods. The fullName call returns "Ana Berg" through this.name, and the caller logs it. The birthday call adds 1 to age, and the next line logs 10. The last line logs all four property names with Object.keys.
Try it Yourself
Edit the code, then press Run.
Runs in your browser โ the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.
Exercise
What does this mean inside a method?