Learn / Programming / JavaScript / Objects, this and Prototypes

JavaScript · Lesson 9 of 15

Objects, this and Prototypes

Object literals, methods, this binding and how prototypes share behaviour.

  • Intermediate
  • 15 min read
  • 3 objectives

Before this lessonLesson 8: Strings, Numbers and Math

What you will learn

  • Write objects with methods
  • Explain this
  • Describe the prototype chain

Your Progress

0 of 15 lessons 0%

  • Lessons0 / 15
  • Completed0
  • Est. time left~ 3 hours

Create a free account to keep your progress on every device.

Objects are bags of properties. When a function lives on an object it is a method, and inside it the keyword this refers to the object it was called on.

Methods and this

"use strict";
const user = {
  name: "Ada",
  greet() {
    return `Hi, I am ${this.name}`;
  },
};
console.log(user.greet());

const loose = user.greet;
try { console.log(loose()); } catch (e) { console.log("lost this"); }
Output
Hi, I am Ada
lost this

this is decided by how a function is called, not where it was written. Detached from its object it loses its owner. Fix it with bind, or use an arrow function, which takes this from the surrounding code.

const user = { name: "Ada", greet() { return this.name; } };
const bound = user.greet.bind(user);
console.log(bound());

const timer = {
  n: 0,
  start() { [1, 2, 3].forEach(() => this.n++); },   // arrow keeps this
};
timer.start();
console.log(timer.n);
Output
Ada
3

Prototypes

Every object has a hidden link to a prototype. When you read a property JavaScript looks on the object, then its prototype, then that object's prototype, up the prototype chain until it finds it or reaches null.

const animal = { eats: true, speak() { return "..."; } };
const dog = Object.create(animal);
dog.bark = () => "Woof";
console.log(dog.eats, dog.bark());
console.log(Object.getPrototypeOf(dog) === animal);
console.log(Object.hasOwn(dog, "eats"));
Output
true Woof
true
false

Handy object tools

const o = { a: 1, b: 2 };
console.log(Object.keys(o), Object.values(o));
console.log(Object.entries(o));
console.log({ ...o, c: 3 });
console.log(Object.fromEntries([["x", 1]]));
const frozen = Object.freeze({ id: 1 });
try { frozen.id = 2; } catch { console.log("frozen!"); }
console.log(frozen.id);
Output
[ 'a', 'b' ] [ 1, 2 ]
[ [ 'a', 1 ], [ 'b', 2 ] ]
{ a: 1, b: 2, c: 3 }
{ x: 1 }
frozen!
1
Up next · Lesson 10Classes and Inheritanceclass syntax, constructors, static members, getters and extends.