Objects, Prototypes and this
Build a precise mental model of JavaScript values, scope, functions, objects, arrays and asynchronous behavior, then implement and debug real utilities from first principles instead of memorizing outputs.
What you will be able to do
#- Read and write object properties and explain property lookup.
- Trace the prototype chain for inherited behavior.
- Predict the value of this under the common call forms.
Overview
#Objects are property bags
An object maps string and symbol keys to values. You can read a property with dot or bracket notation, and bracket notation lets you use a computed key. Reading a missing property returns undefined rather than throwing.
The prototype chain
Every object has an internal link to another object called its prototype. When you read a property the engine checks the object, then its prototype, then the prototype's prototype, until it reaches null. This chain is how inheritance works. Object.create(proto) builds a new object whose prototype is proto, and the class syntax is a readable wrapper over the same mechanism.
const animal = { speak() { return 'sound'; } };
const dog = Object.create(animal);
dog.speak = () => 'woof';
console.log(dog.speak()); // woof, own property wins
console.log(animal.speak()); // sound
this depends on the call
this is set by how a function is called, not where it is defined. A method call sets this to the receiver. A plain call sets this to undefined in strict mode. call, apply and bind set it explicitly. Arrow functions ignore all of this and use the this of the enclosing scope. Losing this usually happens when a method is passed as a callback and called without its receiver.
Classes
The class keyword gives a cleaner syntax for prototypes, constructor functions and inheritance. It does not change the underlying model: methods still live on the prototype, and instances still delegate to it.
Exercises
#Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.
Exercise 1Predict
What does this print when the method is extracted and called on its own?
Read the code, then choose the best answer. The reference explanation stays hidden until you respond. stimulus.javascriptconst user = { name: 'Ada', greet() { return this === user ? this.name : undefined; }, }; const fn = user.greet; console.log(fn());Exercise 2Explain
Explain how `dog.speak()` finds a method that is not an own property of dog.
starter.javascriptconst animal = { speak() { return 'sound'; } }; const dog = Object.create(animal); console.log(dog.speak());Reveal the reference answer
reference.javascriptReading speak on dog first checks dog's own properties. It has none named speak, so the engine follows dog's prototype link to animal and finds speak there. The method runs with this set to dog because the call site was dog.speak().Authored expected output: sound
Property lookup walks the prototype chain until it finds the key or reaches null. The receiver for this is the object before the dot, not the object that owns the method.
Exercise 3Implement
Implement `createCounter(start)` that returns an object with an increment method and a value method, using a closure for state. Running `const c = createCounter(10); c.increment(); console.log(c.value());` should print `11`.
starter.javascriptfunction createCounter(start) { // your code here }Reveal the reference answer
reference.javascriptfunction createCounter(start) { let current = start; return { increment() { current += 1; }, value() { return current; }, }; }Authored expected output: 11
The two methods close over the same current binding, so increment and value observe the same private state without exposing a public property.
Exercise 4Debug
This code is meant to log the user's name from a timer callback but logs undefined. Fix the this binding.
starter.javascriptconst user = { name: 'Ada', start() { setTimeout(function () { console.log(this.name); }, 0); }, }; user.start();Reveal the reference answer
reference.javascriptconst user = { name: 'Ada', start() { setTimeout(() => console.log(this.name), 0); }, }; user.start();Authored expected output: Ada
A regular function passed to setTimeout is called without a receiver, so its this is not user. An arrow function keeps the this of start, which is user.
Exercise 5Test
Write assertions that prove an instance created by a class is an instance of both the class and its base class.
starter.javascriptclass Animal {} class Dog extends Animal {} const dog = new Dog();Reveal the reference answer
reference.javascriptif (!(dog instanceof Dog)) throw new Error('not a Dog'); if (!(dog instanceof Animal)) throw new Error('not an Animal'); if (Object.getPrototypeOf(Dog.prototype) !== Animal.prototype) throw new Error('prototype link wrong'); console.log('prototype chain verified');Authored expected output: prototype chain verified
instanceof walks the prototype chain, so a Dog instance is also an Animal. The third check confirms the chain is wired through the prototypes, not through copied methods.
Exercise 6Interview
Explain the four common ways this is determined, with one example each.
starter.javascriptfunction who() { return this && this.tag; } console.log(who.call({ tag: 'explicit' }));Reveal the reference answer
reference.javascript1. Method call: obj.method() sets this to obj. 2. Plain call: fn() sets this to undefined in strict mode or the global object in sloppy mode. 3. Explicit binding: fn.call(obj), fn.apply(obj) and fn.bind(obj) set this directly. 4. Constructor call: new Fn() creates a fresh object and sets this to it. Arrow functions are a special case that capture this from the enclosing scope.Authored expected output: explicit
A strong answer covers method, plain, explicit and constructor calls, and notes that arrow functions opt out of all four.
Common misconceptions
#- Classes are a different object model from prototypes.
- this is determined by where a function is defined.
- Reading a missing property throws an error.
Follow-up practice
#- javascript-foundations-metaprogramming
- javascript-foundations-arrays-and-iteration
Your progress
#Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.
Verification: authored. Answers and outputs on this page are authored reference material, not executed results.