These are the notes for JavaScript Coding Questions, episode 19, interview and placement practice for people who finished the SyntaxPilot JavaScript course. Last episode built higher-order functions (debounce, throttle, curry, pipe). Today: the keyword everyone gets wrong, this. We write our own call, apply and bind, see why every function already has them (Function.prototype), and solve five output questions on this in normal and arrow functions.
Each question follows the same steps: read the problem, think out loud, the obvious attempt, a real failure, why, the fix, every test case, and the complexity.
Every program was run with Node.js 24 (node main.js), the SyntaxPilot compiler's JavaScript command, and every output below is real. A main.js file run this way is a CommonJS module in sloppy mode (not strict), which matters for this: we point it out where it does.
First: what is this?
Inside a normal function (one written with function or as a method), this is the object the function was called on:
const chef = {
name: "Ravi",
cook(dish) {
return `${this.name} cooks ${dish}`;
},
};
console.log(chef.cook("poha"));
Ravi cooks poha
this is decided when the function is called, not where it is written. The same function can get a different this on every call. call, apply and bind are the three tools that let you choose it.
Q1: Write your own call and apply
Problem. fn.call(obj, a, b) runs fn now, with this set to obj and the arguments a, b. fn.apply(obj, [a, b]) does the same, but the arguments come in one array. Write myCall and myApply.
Real life: a guest chef cooks in your restaurant's kitchen for one evening, then leaves. Your kitchen is unchanged afterwards.
Think out loud: input = a function, an object, some arguments; output = whatever the function returns. Edge cases: the object must not be changed, the object can be null/undefined, or a primitive like 42.
Attempt: copy the method onto the object
const chef = {
name: "Ravi",
cook(dish, mins) {
return `${this.name} cooks ${dish} in ${mins} min`;
},
};
const guest = { name: "Asha" };
console.log(chef.cook("poha", 10));
guest.cook = chef.cook;
console.log(guest.cook("upma", 12));
console.log(Object.keys(guest));
Ravi cooks poha in 10 min
Asha cooks upma in 12 min
[ 'name', 'cook' ]
It works, but we changed guest: it now has a cook key it never had. If guest is saved, compared or looped over, cook shows up where nobody expects it. We want "run cook with this = guest" and leave guest alone.
Why every function can use myCall: Function.prototype
function cook() {}
console.log(Object.getPrototypeOf(cook) === Function.prototype);
console.log(cook.hasOwnProperty("call"));
console.log(Function.prototype.hasOwnProperty("call"));
Function.prototype.hello = function () {
return `hi from ${this.name}`;
};
console.log(cook.hello(), Math.max.hello());
true
false
true
hi from cook hi from max
Every function's prototype (the object it inherits missing properties from) is Function.prototype. call, apply and bind live there, not on each function. Add a method there and every function, even Math.max, can use it. Inside such a method, this is the function it was called on (method-call rule: the thing before the dot). (A function's name property is its name: "cook", "max".)
Attempt 2: a temporary fn property
The trick: put the function on the object as a property, call it as a method (so this becomes the object), then delete the property.
Function.prototype.myCall = function (ctx, ...args) {
ctx.fn = this;
const result = ctx.fn(...args);
delete ctx.fn;
return result;
};
function cook(dish) {
return `${this.name} cooks ${dish}`;
}
const guest = { name: "Asha" };
console.log(cook.myCall(guest, "upma"), Object.keys(guest));
const robot = { name: "Bot-7", fn: "fan mode" };
console.log(cook.myCall(robot, "idli"));
console.log(robot);
Asha cooks upma [ 'name' ]
Bot-7 cooks idli
{ name: 'Bot-7' }
guest is clean now. But the robot lost its own fn property ("fan mode"): we overwrote it, then deleted it. Any string key we pick can clash with a key the object already has.
Fix: a Symbol key, plus null and primitives
Function.prototype.myCall = function (ctx, ...args) {
ctx = ctx == null ? globalThis : Object(ctx);
const key = Symbol("fn");
ctx[key] = this;
const result = ctx[key](...args);
delete ctx[key];
return result;
};
Function.prototype.myApply = function (ctx, args = []) {
return this.myCall(ctx, ...args);
};
function cook(dish, mins) {
return `${this.name} cooks ${dish} in ${mins} min`;
}
const robot = { name: "Bot-7", fn: "fan mode" };
console.log(cook.myCall(robot, "idli", 15));
console.log(robot);
console.log(cook.myApply({ name: "Neha" }, ["dosa", 8]));
function kind() { return typeof this; }
console.log(kind.myCall(42), kind.call(42));
console.log(Math.max.myApply(null, [3, 9, 4]));
Bot-7 cooks idli in 15 min
{ name: 'Bot-7', fn: 'fan mode' }
Neha cooks dosa in 8 min
object object
9
Symbol("fn")creates a brand-new key that is never equal to any other key, so it can't clash. (The text"fn"is only a label for debugging.)ctx == nullis true for bothnullandundefined; then we useglobalThis, the global object, as sloppy-modecalldoes.Object(42)wraps a primitive in an object (aNumberobject), because you can't add properties to a primitive. That's whytypeof thisis"object", same as the realcallin sloppy mode.myApplyjust spreads the array intomyCall.args = []handlesfn.myApply(obj)with no array.
Complexity: copying n arguments is O(n) time and space; adding and deleting one property is O(1).
Q2: Write your own bind
Problem. fn.bind(obj, ...preset) does not run fn. It returns a new function whose this is fixed to obj, with preset arguments filled in first. Write myBind.
Real life: you hand a method to someone who will call it later: setTimeout, a button click handler, an event listener.
The problem: a method passed around loses its object
const shop = {
name: "Chai Point",
open() {
console.log(`${this.name} is open`);
},
};
shop.open();
setTimeout(shop.open, 0);
const later = shop.open;
later();
Chai Point is open
undefined is open
undefined is open
shop.open without brackets is just the function; the object isn't attached. later() is a plain call, so this is globalThis (sloppy mode), which has no name. In Node, setTimeout calls the callback with this set to its internal Timeout object, which has no name either. Either way: undefined.
Real life: a shop hands a courier a note that says "we are open", with no shop name on it. Delivered later, nobody knows who sent it. The fix is to pre-address the envelope: that's bind.
Attempt: use this inside the returned function
Function.prototype.myBind = function (ctx, ...preset) {
return function (...later) {
return this.apply(ctx, [...preset, ...later]);
};
};
const shop = { name: "Chai Point" };
function open(time) {
console.log(`${this.name} opens at ${time}`);
}
const openShop = open.myBind(shop);
openShop("7 am");
/tmp/main.js:3
return this.apply(ctx, [...preset, ...later]);
^
TypeError: this.apply is not a function
at /tmp/main.js:3:17
(The compiler shows the full stack trace; the path is shortened here.) The inner function is called later as openShop("7 am"), a plain call, so its this is globalThis, not open. Every normal function gets its own this: we lost this in exactly the way we're trying to fix.
Fix: save this first
Function.prototype.myBind = function (ctx, ...preset) {
const fn = this;
return function (...later) {
return fn.apply(ctx, [...preset, ...later]);
};
};
const shop = { name: "Chai Point" };
function open(time, day) {
console.log(`${this.name} opens at ${time} on ${day}`);
}
const openShop = open.myBind(shop);
openShop("7 am", "Monday");
const sunday = open.myBind(shop, "9 am");
sunday("Sunday");
setTimeout(open.myBind({ name: "Dosa Hut" }, "8 am"), 0, "Tuesday");
const again = openShop.myBind({ name: "Other" });
again("6 am", "Friday");
Chai Point opens at 7 am on Monday
Chai Point opens at 9 am on Sunday
Chai Point opens at 6 am on Friday
Dosa Hut opens at 8 am on Tuesday
const fn = thisruns insidemyBind, wherethisisopen. The returned function readsfnfrom its closure (episode 17).- Preset arguments:
open.myBind(shop, "9 am")fixes the first argument now; the rest come later. Fixing some arguments now is called partial application. setTimeout(fn, 0, "Tuesday"): extra arguments tosetTimeoutare passed tofn. That line prints last because it waits for the timer.- A bound function can't be re-bound.
openShop.myBind(Other)still saysChai Point: the newctxis used asthisfor the outer bound function, which ignores itsthisand callsopenwithshop. The realbindbehaves the same way.
Complexity: bind itself is O(1); each call copies the preset and later arguments: O(n) time and space.
Q3: Output questions on this
Rule for normal functions: this comes from how the function is called. Arrow functions have no this of their own: they use the this of the place where they were written (the surrounding function, or the module).
Predict all five before reading the output.
const train = {
name: "Rajdhani",
normal() { return this.name; },
arrow: () => this.name,
later() {
const inner = function () { return this.name; };
const arrowIn = () => this.name;
return [inner(), arrowIn()];
},
};
console.log("1:", train.normal());
console.log("2:", train.arrow());
console.log("3:", train.later());
const go = train.normal;
console.log("4:", go());
console.log("5:", train.arrow.call(train));
1: Rajdhani
2: undefined
3: [ undefined, 'Rajdhani' ]
4: undefined
5: undefined
- A method called on
train:thisistrain. - The arrow was written at the top level of the file. An object literal
{ }is not a function, so it doesn't give the arrow athis. At the top level of a CommonJS file,thisismodule.exports(an empty object{}), which has noname. inner()is a plain call:thisisglobalThis, noname.arrowInwas written insidelater, so it borrowslater'sthis:train.- The method was pulled away from its object: a plain call (the
setTimeouttrap again). call,applyandbindcan't change an arrow'sthis.
Where it bites: callbacks inside methods
const train = {
name: "Rajdhani",
stops: ["Delhi", "Kota", "Mumbai"],
announce() {
this.stops.forEach(function (s) {
console.log(`${this.name} stops at ${s}`);
});
},
announceArrow() {
this.stops.forEach((s) => console.log(`${this.name} stops at ${s}`));
},
};
train.announce();
train.announceArrow();
const go = train.announceArrow.bind(train);
setTimeout(go, 0);
undefined stops at Delhi
undefined stops at Kota
undefined stops at Mumbai
Rajdhani stops at Delhi
Rajdhani stops at Kota
Rajdhani stops at Mumbai
Rajdhani stops at Delhi
Rajdhani stops at Kota
Rajdhani stops at Mumbai
forEach calls a normal callback with no this (we didn't pass its second argument, thisArg). The arrow callback borrows announceArrow's this. The bound method survives setTimeout.
The four rules, in order
| Check | How it was called | this is |
|---|---|---|
| 1 | new Fn() |
the brand-new object |
| 2 | fn.call(obj), fn.apply(obj), fn.bind(obj)() |
obj |
| 3 | obj.method() |
obj, the object before the dot |
| 4 | a plain call fn() |
undefined in strict mode, globalThis otherwise |
| — | an arrow function | skips all four: the this of where it was written |
Strict mode is a stricter version of JavaScript turned on by "use strict", and automatically inside classes and ES modules. In strict mode a plain call gives this === undefined, so this.name throws a TypeError instead of quietly giving undefined.
Complexity summary
| Function | Time | Space |
|---|---|---|
myCall |
O(n) for n arguments | O(n) |
myApply |
O(n) | O(n) |
myBind |
O(1) to bind; O(n) per call | O(n) |
Common mistakes (and the exact outputs)
| Mistake | Code | What you see | Why | Fix |
|---|---|---|---|---|
| Copying a method to borrow it | guest.cook = chef.cook |
[ 'name', 'cook' ] |
the object is changed | chef.cook.call(guest, …) |
A string key in myCall |
ctx.fn = this |
{ name: 'Bot-7' } (lost fn) |
the key can clash | a Symbol key |
| Passing a method | setTimeout(shop.open, 0) |
undefined is open |
it lost its object | shop.open.bind(shop) or () => shop.open() |
this inside bind's inner function |
this.apply(ctx, …) |
TypeError: this.apply is not a function |
the inner function has its own this |
const fn = this; outside |
call on an arrow |
train.arrow.call(train) |
undefined |
arrows have no own this |
write a normal method |
| A normal callback in a method | forEach(function () { this.name }) |
undefined stops at Delhi |
plain call inside forEach |
an arrow callback, or forEach(fn, this) |
Mini project: a ticket counter with event callbacks
A tiny "button" that stores callbacks and calls them later, the way the browser does. The counter's method is passed with myBind, with a preset argument.
Function.prototype.myBind = function (ctx, ...preset) {
const fn = this;
return function (...later) {
return fn.apply(ctx, [...preset, ...later]);
};
};
const button = {
handlers: [],
onClick(fn) { this.handlers.push(fn); },
click(e) { this.handlers.forEach((fn) => fn(e)); },
};
const counter = {
station: "Kota",
sold: 0,
sell(kind, e) {
this.sold++;
console.log(`${this.station}: ${kind} ticket #${this.sold} (${e})`);
},
};
button.onClick(counter.sell.myBind(counter, "sleeper"));
button.onClick((e) => console.log("log:", e));
button.click("click 1");
button.click("click 2");
console.log("sold:", counter.sold);
Kota: sleeper ticket #1 (click 1)
log: click 1
Kota: sleeper ticket #2 (click 2)
log: click 2
sold: 2
Without myBind, fn(e) would be a plain call and this.sold++ would add 1 to globalThis.sold (undefined → NaN).
Your turn: myBind that works with new (solution)
Problem. The real bind has one more rule: if the bound function is called with new, the bound this is ignored and a new object is built (preset arguments still apply).
Function.prototype.myBind = function (ctx, ...preset) {
const fn = this;
function bound(...later) {
if (new.target) {
return new fn(...preset, ...later);
}
return fn.apply(ctx, [...preset, ...later]);
}
if (fn.prototype) bound.prototype = fn.prototype;
return bound;
};
function Point(x, y) {
this.x = x;
this.y = y;
}
const P = Point.myBind({ ignored: true }, 1);
const p = new P(2);
console.log(p, p instanceof Point, p instanceof P);
const R = Point.bind({ ignored: true }, 1);
console.log(new R(2));
Point { x: 1, y: 2 } true true
Point { x: 1, y: 2 }
new.target is set (to the function) only when a function is called with new; otherwise it's undefined. Then we build the object with new fn(...). Sharing the prototype makes instanceof work for both Point and P.
Practice questions (with solutions)
1. Borrow an array method for an array-like object. arguments and { 0: "a", 1: "b", length: 2 } look like arrays but have no join.
Solution
const arrayLike = { 0: "chai", 1: "vada", 2: "poha", length: 3 };
console.log(Array.prototype.join.call(arrayLike, " + "));
function total() {
return Array.prototype.reduce.call(arguments, (a, b) => a + b, 0);
}
console.log(total(10, 20, 30));
chai + vada + poha
60
Array methods only need length and numbered keys, so call lets an array-like object borrow them. (Today you'd usually write Array.from(arrayLike) or use rest parameters.)
2. Why does this print NaN? Fix it two ways.
const meter = {
units: 0,
start() {
setTimeout(function () {
this.units += 5;
console.log(this.units);
}, 0);
},
};
meter.start();
NaN
Solution
The callback is a normal function, so this is not meter (in Node it's the Timeout object, whose units is undefined; undefined + 5 is NaN). Use an arrow, or bind:
const meter = {
units: 0,
start() {
setTimeout(() => {
this.units += 5;
console.log("arrow:", this.units);
}, 0);
setTimeout(function () {
this.units += 5;
console.log("bind:", this.units);
}.bind(this), 0);
},
};
meter.start();
arrow: 5
bind: 10
3. Predict the output: this in a class and a detached method.
class Bus {
constructor(route) { this.route = route; }
show() { return this.route; }
}
const b = new Bus("500D");
console.log(b.show());
const show = b.show;
try {
console.log(show());
} catch (err) {
console.log(err.constructor.name + ":", err.message);
}
Answer
500D
TypeError: Cannot read properties of undefined (reading 'route')
Class bodies are always strict mode, so a plain call gives this === undefined, and reading .route from undefined throws.
4. Five more this puzzles.
const app = {
name: "Zomato-like",
a() { return this.name; },
b: function () { return (() => this.name)(); },
c() { return [1].map(function () { return this; }, "thisArg")[0]; },
d() { return (0, this.a)(); },
};
console.log(app.a(), "|", app.b(), "|", typeof app.c(), "|", app.d());
const e = app.a.bind(app).bind({ name: "other" });
console.log(e());
Answer
Zomato-like | Zomato-like | object | undefined
Zomato-like
a: method call. b: the arrow borrows b's this. c: map's second argument is the callback's this; the string is wrapped into an object in sloppy mode, so typeof is "object". d: the comma operator (0, this.a) returns just the function, so the call is plain. e: the first bind wins.
5. myCall without Symbol, for old browsers: make a key that's very unlikely to clash.
Solution
Function.prototype.myCall = function (ctx, ...args) {
ctx = ctx == null ? globalThis : Object(ctx);
let key = "__fn";
while (key in ctx) key += "_";
ctx[key] = this;
const result = ctx[key](...args);
delete ctx[key];
return result;
};
function greet() { return `${this.name}, ${Object.keys(this)}`; }
const o = { name: "Asha", __fn: 1 };
console.log(greet.myCall(o));
console.log(o);
Asha, name,__fn,__fn_
{ name: 'Asha', __fn: 1 }
The loop keeps adding _ until the key is free, so nothing is overwritten. But the temporary key is visible while the function runs (see Object.keys), which is why Symbol is the better answer.
Quick quiz
const bus = { n: "Volvo", get() { return this.n; } };
const car = { n: "Nano", get: bus.get };
const f = bus.get.bind(bus);
console.log(car.get(), f.call(car));
A) Volvo Volvo B) Nano Volvo C) Nano Nano D) undefined Volvo
Answer
B, output Nano Volvo. car.get() is a method call on car, so this is car. f is bound to bus, and call can't change a bound function's this.
Interview questions
- Difference between
call,applyandbind?callandapplyrun the function now (arguments one by one vs in an array);bindreturns a new function to run later. - How does your
myCallsetthis? It puts the function on the object under a uniqueSymbolkey, calls it as a method, then deletes the key. - Why
Symboland notctx.fn? A string key can overwrite and then delete a real property of the object. - What happens when you
binda bound function? Nothing changes: the first boundthiswins (extra preset arguments are still added). - What is
thisin an arrow function? Thethisof the surrounding code where the arrow was written;call,apply,bindcan't change it. - Why does
setTimeout(obj.method)losethis? The method is passed without its object, then called as a plain function. - What are the four
thisrules, in order?new, explicit (call/apply/bind), implicit (obj.method()), default (plain call). - What is
Function.prototype? The object every function inherits from;call,apply,bindandtoStringlive there. - What is partial application? Fixing some arguments now and returning a function for the rest, like
open.bind(shop, "9 am").
Glossary
| Term | Meaning |
|---|---|
this |
Inside a normal function: the object the function was called on |
| Normal function | A function written with function or as a method name() {} |
| Arrow function | (x) => …: has no own this, arguments or prototype |
| Method | A function stored as a property of an object |
| Plain call | Calling a function on its own, fn(), not obj.fn() |
fn.call(obj, a, b) |
Run fn now with this = obj |
fn.apply(obj, [a, b]) |
Like call, arguments in one array |
fn.bind(obj, a) |
A new function with this fixed to obj (and a preset) |
| Prototype | The object another object inherits missing properties from |
Function.prototype |
The prototype of every function; holds call, apply, bind |
Symbol() |
A unique value; as a key, it can't clash with any other key |
globalThis |
The global object (in Node, the one with setTimeout, console) |
Object(value) |
Wraps a primitive (like 42) in an object |
| Primitive | A plain value that isn't an object: number, string, boolean, null, undefined, symbol, bigint |
| Closure | A function plus the variables it remembers (episode 17) |
| Partial application | Fixing some arguments now, the rest later |
| Preset arguments | The arguments given to bind after the object |
| Strict mode | Stricter JavaScript ("use strict", classes, ES modules); a plain call gives this === undefined |
| Sloppy mode | The non-strict default for CommonJS files; a plain call gives this === globalThis |
| CommonJS module | Node's original module format; top-level this is module.exports |
new.target |
Inside a function, set only when it's called with new |
thisArg |
An optional argument (in forEach, map…) that becomes the callback's this |
| Array-like | An object with length and numbered keys, but no array methods |
| Big-O | How the work grows with the input size |
Summary
thisis decided when a function is called. Four rules in order:new,call/apply/bind,obj.method(), plain call. Arrow functions skip them all and use thethisof where they were written.- Every function inherits
call,applyandbindfromFunction.prototype, so a method added there works on every function. myCallputs the function on the object under aSymbolkey, calls it, and deletes it;null→globalThis, primitives →Object(value).myApplyismyCallwith an array.- A method passed around loses its object.
myBindsavesfn = thisfirst and returns a function that callsfn.apply(ctx, [...preset, ...later]). A bound function can't be re-bound. - Next episode: polyfill questions: write your own
map,filterandreduce.