Objects can contain methods, which are functions defined within the object.
Define a method within an object:
let person = {
name: "Alice",
greet: function() {
console.log("Hello, " + this.name + "!");
}
};
person.greet();
this
Keywordthis
refers to the object that the method belongs to.
Create an object representing a calculator with methods for add
and subtract
. Call each method and log the results.
this
refer to in a method?Answers: A function in an object; use dot notation; the object itself.