These are the notes for JavaScript episode 17. Episode 16 left two mysteries: check is not stored inside q1, yet q1.check() works; and sometimes this suddenly becomes undefined. Here you'll solve both. You'll discover own properties, the prototype and the prototype chain, build a chain yourself with Object.create, see that a class is a constructor function plus prototype methods, and learn the four rules of this, how callbacks lose it, and how bind, call and arrow functions fix it. Every example runs as-is in the SyntaxPilot compiler (language: JavaScript, Node.js), and every output and error is real Node.js 24 output.
Builds on: objects (episode 8), functions and arrow functions (9), map and forEach (11), classes (16).
Mystery 1: where does check live?
The real-life idea: borrowing a ladder
You need a ladder. You look in your own flat first. Not there? You ask the society office, and use theirs as if it were yours. Not there either? The municipal office. If nobody up the chain has one, the answer is simply "not available". JavaScript looks up properties exactly like this.
class Question {
constructor(text, answer) { this.text = text; this.answer = answer; }
check(given) { return given.trim().toUpperCase() === this.answer; }
}
const q1 = new Question("Capital of India?", "B");
console.log(Object.keys(q1));
console.log(q1.hasOwnProperty("text"), q1.hasOwnProperty("check"));
console.log(Object.getPrototypeOf(q1) === Question.prototype);
console.log(Object.getOwnPropertyNames(Question.prototype));
console.log(q1.toString());
console.log(Object.getPrototypeOf(Question.prototype) === Object.prototype);
console.log(Object.getPrototypeOf(Object.prototype));
console.log(q1.fly);
[ 'text', 'answer' ]
true false
true
[ 'constructor', 'check' ]
[object Object]
true
null
undefined
Line by line:
Object.keys(q1)lists only own properties (stored in the object itself):textandanswer.hasOwnProperty("check")isfalse:checkis not inq1, just as the ladder isn't in your flat.Object.getPrototypeOf(q1)isQuestion.prototype: the object JavaScript asks next (the society office). The class putconstructorandcheckthere, once.toString()works although we never wrote it: it lives onObject.prototype, the last stop for ordinary objects (the municipal office).- The prototype of
Object.prototypeisnull: the end of the chain. q1.flyisn't found anywhere, so it'sundefined, not an error. (Calling it,q1.fly(), would beTypeError: q1.fly is not a function.)
The prototype chain
q1 ──► Question.prototype ──► Object.prototype ──► null
text, answer check() toString(), hasOwnProperty()
- Own property: stored in the object itself.
- Prototype: the object JavaScript asks next when a property is missing. Every object has a hidden link to one (or to
null). - Prototype chain: the series of those links. A lookup walks it until it finds the property or reaches
null.
It's the same for built-ins:
const arr = [3, 1, 2];
console.log(Object.getPrototypeOf(arr) === Array.prototype, arr.hasOwnProperty("map"));
console.log(Object.getPrototypeOf(Array.prototype) === Object.prototype);
true false
true
map and filter (episode 11) live on Array.prototype, not inside your array.
You may see
q1.__proto__in old code. It's the same link, butObject.getPrototypeOf(q1)is the modern, recommended way to read it.
Build a chain yourself: Object.create
Object.create(proto) makes a new, empty object whose prototype is proto. No class needed.
const chai = { name: "Masala chai", price: 20 };
const special = Object.create(chai);
special.price = 25;
console.log(special.name, special.price, chai.price);
console.log(Object.keys(special));
delete special.price;
console.log(special.price);
Masala chai 25 20
[ 'price' ]
20
special.nameis found onchai, through the chain.special.price = 25creates an own property that hideschai.price. This is called shadowing.chaiitself is unchanged.- After
delete special.price, the lookup finds nothing inspecialand walks up tochaiagain:20. - Writing a property always writes to the object itself; only reading walks the chain.
A class under the hood: constructor functions
Before class arrived (ES2015), everyone wrote constructor functions: normal functions called with new, with methods attached by hand to the function's prototype object.
function Question(text, answer) {
this.text = text;
this.answer = answer;
}
Question.prototype.check = function (given) {
return given.trim().toUpperCase() === this.answer;
};
const q1 = new Question("Capital of India?", "B");
const q2 = new Question("2 + 2 * 2 = ?", "A");
console.log(q1, q1.check("b"));
console.log(q1.check === q2.check, q1 instanceof Question);
Question { text: 'Capital of India?', answer: 'B' } true
true true
Same result as the class. new F() does four things: creates an empty object, sets its prototype to F.prototype, runs F with this = that object, and returns it. A class is a cleaner syntax for the same thing (plus safety: a class can't be called without new, and its body is always strict mode).
Adding to a prototype reaches every object
class Question {
constructor(text, answer) { this.text = text; this.answer = answer; }
check(given) { return given.trim().toUpperCase() === this.answer; }
}
const q1 = new Question("Capital of India?", "B");
const q2 = new Question("2 + 2 * 2 = ?", "A");
Question.prototype.hint = function () { return `Starts with option ${this.answer}`; };
console.log(q1.hint(), "|", q2.hint());
q2.hint = function () { return "No hints for you!"; };
console.log(q1.hint(), "|", q2.hint());
Starts with option B | Starts with option A
Starts with option B | No hints for you!
hint was added after q1 and q2 were made, and both got it, because they look it up on the prototype at call time. q2's own hint then shadows the shared one for q2 only.
Don't modify built-in prototypes (Array.prototype.myMap = ...): every array in the program, and every library, sees the change, and names can clash with future JavaScript features. Change prototypes you own.
Mystery 2: this goes missing
class Question {
constructor(text, answer) { this.text = text; this.answer = answer; }
check(given) { return given.trim().toUpperCase() === this.answer; }
}
const q1 = new Question("Capital of India?", "B");
console.log(q1.check("b"));
const check = q1.check;
console.log(check("b"));
true
/tmp/.../main.js:3
check(given) { return given.trim().toUpperCase() === this.answer; }
^
TypeError: Cannot read properties of undefined (reading 'answer')
The same function works with q1.check("b") and crashes with check("b"). this is not fixed when a function is written; it is decided each time the function is called.
The real-life idea: whose house is "my house"?
When Asha says "my house", it means Asha's house; when Ravi says it, Ravi's. The word is the same, the speaker decides. this works the same way.
The four rules of this
| Rule | How it's called | this is |
Real life |
|---|---|---|---|
| 1. Method call | q1.check("b") |
the object before the dot: q1 |
Asha says "my house" |
| 2. Plain call | check("b") |
undefined in strict code (classes, ES modules); globalThis in sloppy code |
an unsigned note |
3. new |
new Question(...) |
the brand-new object | a newborn's first "my" |
4. call / apply / bind |
check.call(obj, "b") |
whatever you pass | signing on someone's behalf |
And one exception: arrow functions don't have their own this; they use the this of the place where they were written.
Strict mode is a safer setting of JavaScript that turns some silent mistakes into errors. Class bodies and ES modules are always strict; elsewhere you turn it on with the string "use strict"; at the top of a file or function. Sloppy mode is the old default, without those protections. globalThis is the global object (in Node, it holds things like console and setTimeout).
function whoAmI() {
return this;
}
console.log(whoAmI() === globalThis);
function strictWho() {
"use strict";
return this;
}
console.log(strictWho());
const stall = { name: "Ramesh's stall", whoAmI };
console.log(stall.whoAmI() === stall);
true
undefined
true
One function, three calls, three different this values. In sloppy code a plain call silently gives the global object, which hides bugs; strict mode makes it undefined, so the bug shows up as an error.
Callbacks lose this
A callback is a function you hand to someone else to call later, like the function you give to map.
class Question {
constructor(text, answer) { this.text = text; this.answer = answer; }
check(given) { return given.trim().toUpperCase() === this.answer; }
}
const q1 = new Question("Capital of India?", "B");
const answers = ["b", "C", " B "];
console.log(answers.map(q1.check));
TypeError: Cannot read properties of undefined (reading 'answer')
We handed map only the function, not q1. map calls it as a plain function (rule 2).
Fixes:
console.log(answers.map((a) => q1.check(a))); // arrow wrapper: we call it with the dot
const bound = q1.check.bind(q1); // bind: a new function with this locked to q1
console.log(answers.map(bound));
console.log(q1.check.call({ answer: "C" }, "c")); // call: run once with a chosen this
[ true, false, true ]
[ true, false, true ]
true
fn.bind(obj)returns a new function whosethisis alwaysobj.fn.call(obj, a, b)runsfnonce, right now, withthis = objand the arguments listed.fn.apply(obj, [a, b])is the same ascall, but takes the arguments as an array.
The same trap appears with timers: setTimeout(this.done, 1000) passes only the function. Use setTimeout(() => this.done(), 1000) or setTimeout(this.done.bind(this), 1000).
Arrow functions and this
Bad as object methods:
const stall = {
name: "Ramesh's stall",
greet: () => `Welcome to ${this.name}`,
hello() { return `Welcome to ${this.name}`; },
};
console.log(stall.greet());
console.log(stall.hello());
Welcome to undefined
Welcome to Ramesh's stall
The arrow was written at the top level of the file, so its this is the file's this (in a CommonJS file, the empty module.exports object), not stall. Use normal method syntax for methods.
Great inside methods:
class Classroom {
constructor(teacher, students) {
this.teacher = teacher;
this.students = students;
}
rollCall() {
this.students.forEach(function (name) {
console.log(`${this.teacher}: ${name}?`);
});
}
}
new Classroom("Meena ma'am", ["Asha", "Ravi"]).rollCall();
TypeError: Cannot read properties of undefined (reading 'teacher')
The inner function is called by forEach as a plain call, so it gets its own this = undefined. Change it to an arrow, this.students.forEach((name) => { ... }), and it uses rollCall's this, the classroom:
Meena ma'am: Asha?
Meena ma'am: Ravi?
Common mistakes (and what really happens)
| You wrote | What happens | Why | Fix |
|---|---|---|---|
const check = q1.check; check("b") |
TypeError: Cannot read properties of undefined (reading 'answer') |
plain call: this is undefined |
q1.check("b") or q1.check.bind(q1) |
answers.map(q1.check) |
same TypeError | map calls it without q1 |
answers.map((a) => q1.check(a)) |
forEach(function (name) { this.teacher ... }) inside a method |
TypeError: Cannot read properties of undefined (reading 'teacher') |
the inner function has its own this |
use an arrow function |
greet: () => this.name |
(no error) Welcome to undefined |
arrows have no own this |
greet() { ... } |
q1.fly() |
TypeError: q1.fly is not a function |
not found anywhere on the chain | check the name / add the method |
Array.prototype.myMap = ... |
(no error) clashes later | every array and library sees it | a normal function or your own class |
expecting Object.keys(q1) to list methods |
(no error) only own properties | methods live on the prototype | Object.getOwnPropertyNames(Question.prototype) |
Mini project: a tiny inheritance chain by hand
const animal = {
describe() { return `${this.name} says ${this.sound}`; },
};
const dog = Object.create(animal);
dog.sound = "woof";
const puppy = Object.create(dog);
puppy.name = "Bruno";
puppy.sound = "yip";
console.log(puppy.describe());
let obj = puppy;
const chain = [];
while (obj !== null) {
chain.push(Object.keys(obj).join(",") || "(no own keys)");
obj = Object.getPrototypeOf(obj);
}
console.log(chain.join(" -> "));
Bruno says yip
name,sound -> sound -> describe -> (no own keys)
describe is found two links up (on animal), but this is puppy, the object before the dot, so it uses puppy's own name and sound. The last link is Object.prototype, whose methods are not listed by Object.keys because they are not enumerable.
Practice
- Print the whole prototype chain of
[1, 2](hint: loop withObject.getPrototypeOfuntilnull, and compare each link withArray.prototypeandObject.prototype). - Rewrite this class as a constructor function:
class Chai { constructor(size) { this.size = size; } price() { return this.size === "big" ? 30 : 20; } }. - Fix the bug:
class Timer { constructor(label) { this.label = label; } start() { setTimeout(this.done, 10); } done() { console.log(${this.label} finished); } }.
Solutions
1.
let link = [1, 2];
while (link !== null) {
link = Object.getPrototypeOf(link);
console.log(link === Array.prototype ? "Array.prototype" : link === Object.prototype ? "Object.prototype" : link);
}
Array.prototype
Object.prototype
null
2.
function Chai(size) {
this.size = size;
}
Chai.prototype.price = function () {
return this.size === "big" ? 30 : 20;
};
console.log(new Chai("big").price(), new Chai("small").price());
30 20
setTimeout(this.done, 10)hands over only the function. The original printsundefined finished(Node's timer calls it with the timer object asthis). Fix:
class Timer {
constructor(label) { this.label = label; }
start() { setTimeout(this.done.bind(this), 10); }
done() { console.log(`${this.label} finished`); }
}
new Timer("Chai").start();
Chai finished
Quick quiz
What does this print?
const base = { greet() { return `Hi ${this.name}`; } };
const asha = Object.create(base);
asha.name = "Asha";
console.log(asha.greet(), asha.hasOwnProperty("greet"));
- A.
Hi Asha false - B.
Hi Asha true - C.
Hi undefined false - D.
TypeError
Answer
A. greet is found on the prototype (base), but this is the object before the dot, asha. greet is not asha's own property, so false. Where a method lives and what this is are two separate questions.
Interview questions
- What is a prototype? What is the prototype chain? Where does it end?
- What is the difference between an own property and an inherited one? How do you check?
- What does
Object.create(proto)do? What isObject.create(null)useful for? - What does
newdo, step by step, with a constructor function? - Is a JavaScript class "real" classical inheritance? (It's syntax over prototypes.)
- What is property shadowing?
- How is
thisdecided? List the rules. - What is the difference between
call,applyandbind? - Why do arrow functions behave differently with
this? When should you not use them? - Why is modifying
Array.prototypea bad idea?
Glossary
| Term | Meaning | Example |
|---|---|---|
| Own property | a property stored in the object itself | q1.text |
| Inherited property | a property found on the prototype chain | q1.check |
| Prototype | the object JavaScript asks next when a property is missing | Question.prototype |
| Prototype chain | the links from an object to its prototype, its prototype's prototype, ... up to null |
q1 → Question.prototype → Object.prototype → null |
Object.prototype |
the last prototype of ordinary objects; has toString, hasOwnProperty |
q1.toString() |
Object.getPrototypeOf(x) |
returns x's prototype |
Object.getPrototypeOf(q1) |
hasOwnProperty(name) |
true if the property is the object's own |
q1.hasOwnProperty("check") → false |
Object.create(proto) |
makes a new object whose prototype is proto |
Object.create(chai) |
| Shadowing | an own property hides one with the same name on the prototype | special.price = 25 |
| Constructor function | a normal function used with new to build objects (pre-class style) |
function Question(text) { this.text = text; } |
F.prototype |
the object that instances made by new F() link to |
Question.prototype.check = ... |
this |
the object a function is working on, decided by how it's called | q1.check() → this is q1 |
| Method call | calling a function through an object, with a dot | q1.check("b") |
| Plain call | calling a function on its own, no dot | check("b") |
| Strict mode | a safer JavaScript setting; plain calls get this = undefined |
"use strict";, classes, ES modules |
| Sloppy mode | the old default without strict mode's protections | an ordinary script file |
globalThis |
the global object | globalThis.setTimeout |
| Callback | a function passed to another function to be called later | answers.map(fn) |
bind(obj) |
returns a new function with this locked to obj |
q1.check.bind(q1) |
call(obj, ...args) |
runs a function once with this = obj |
check.call(q2, "a") |
apply(obj, [args]) |
like call, arguments as an array |
check.apply(q2, ["a"]) |
Arrow function this |
arrows use the this of where they were written |
forEach((n) => this.teacher) |
Summary
- Objects have own properties and a hidden link to a prototype. A missing property is looked up along the prototype chain until
null; not found meansundefined. - Class methods live once on
ClassName.prototype; that's why they're shared. Object.create(proto)builds a chain by hand; own properties shadow inherited ones.- A class is a constructor function plus methods on its prototype, with extra safety.
thisis decided by the call: the object before the dot, a plain call (undefinedin strict code),new, orcall/apply/bind.- Passing a method as a callback loses
this: wrap it in an arrow orbindit. - Arrow functions have no own
this: bad as object methods, perfect as callbacks inside methods.
Next episode: modules. Our files are getting long; you'll split a program into files with require/module.exports and import/export.