Tsallaka zuwa abun ciki
Justice Tech School

Object Methods and this

A function stored in an object is a method. Inside a method, this refers to the object it was called on. Object.keys, Object.values and Object.entries list an object's contents.

Be careful: if you pull a method out of its object and call it alone, this is lost.

Example
const car = {
  brand: "Toyota",
  speed: 0,
  accelerate(amount) {
    this.speed += amount;
    return this.brand + " is going " + this.speed;
  },
};
console.log(car.accelerate(30));
console.log(Object.keys(car));
console.log(Object.values(car).length);

Exercise

Refer to the current object.

greet() { return .name; }

Quiz Test

Inside a method, what does this usually refer to?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.