Functions as Properties
Methods are functions stored on objects.
They can access other properties using this.
JavaScript Tutorial
Object methods are functions attached to objects, used to operate on their data.
They often rely on this to access other properties.
Methods keep logic close to the data it uses, which makes code more readable.
Understanding this inside methods prevents bugs.
const obj = { method() { ... } }
obj.method()const user = {
name: "Ava",
greet: function() {
return "Hi " + this.name;
}
};
console.log(user.greet());Methods can access properties via this.
const user = {
name: "Ava",
greet() {
return "Hi " + this.name;
}
};
console.log(user.greet());Method shorthand is concise.
Methods are functions stored on objects.
They can access other properties using this.
You can define methods using shorthand syntax.
It makes objects cleaner and easier to read.
this refers to the object the method is called on.
Be careful when passing methods as callbacks.
const user = {
name: "Ava",
greet() {
return "Hi " + this.name;
}
};
const fn = user.greet;
console.log(fn()); // this is undefined in strict modethis depends on call site.
const user = {
name: "Ava",
greet() {
return "Hi " + this.name;
}
};
const bound = user.greet.bind(user);
console.log(bound());bind fixes this to the object.
Without
const greet = function(user) {
return "Hi " + user.name;
};With
const user = {
name: "Ava",
greet() {
return "Hi " + this.name;
}
};Arrow functions do not have their own this.
Use bind or wrap in another function.
Store data as properties, logic as methods.
It refers to the object that called the method.
Arrows do not have their own this.
Use bind or call the method on the object.
Practice: Create an object with a method that returns a full name.
const user = { first: "Ava", last: "Roy" };
// TODO: add fullName method
One Possible Solution
const user = {
first: "Ava",
last: "Roy",
fullName() {
return this.first + " " + this.last;
}
};
console.log(user.fullName());A function stored as an object property.
Yes, this refers to the object the method is called on.
Usually no, because arrows do not bind this.
Try calling the method after changing the name.