Skip to content
Tutorials Center
My learning

Topics

Lesson 7 of 77 ยท JavaScript Interview Questions

JavaScript: this, Prototypes and Classes

Answer the classic JavaScript interview questions on this binding, call/apply/bind, the prototype chain, class syntax and private fields, with runnable examples.

this and prototypes are favorite interview topics because they expose whether you understand how JavaScript really works or only how it looks. Interviewers rarely ask "what is a prototype?" in the abstract. They show a small snippet and ask "what does this print, and why?"

This lesson gives you the rules you need to answer those questions out loud. If you want the full teaching version first, read this, call, apply and bind, prototypes and classes. Here we focus on the answers. If you want a reusable answer structure, see A Framework for Answering Any Question.

How this gets its value

The key sentence to say in an interview: this is decided by how a function is called, not where it is written. The exception is the arrow function, which has no this of its own and uses the one from the surrounding code.

Four ways to set this

new this is the fresh object.
Explicit call, apply and bind choose it.
Method call this is the object before the dot.
Plain call undefined in strict mode.

Check them in this order. Arrow functions skip all four.

1 / 2
JS The four rules and the lost this

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The "lost this" in the last lines is the most common bug behind this question. Passing user.whoAmI as a callback copies only the function. The user. part is gone, so the call becomes a plain call.

Arrow functions inside methods

A typical question: "Why does this work inside an arrow function in a method but not inside a regular function?"

JS Arrow function versus regular function

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The arrow function does not receive its own this, so it finds the one belonging to startArrow. Equally, do not use an arrow function as an object method when you need this to be that object.

call, apply and bind

All three set this explicitly. Remember them like this:

  • fn.call(thisArg, a, b) runs the function now, arguments listed one by one.
  • fn.apply(thisArg, [a, b]) runs the function now, arguments in an array.
  • fn.bind(thisArg, a) does not run it. It returns a new function with this (and optional leading arguments) fixed.
JS call, apply, bind

Press Run (or Ctrl + Enter) to see the console output here.

No output.

A bound function ignores later bind calls, but new can still override it. That is rarely asked, but it shows depth.

The prototype chain

Every object has an internal link to another object, its prototype. When you read obj.prop and obj has no own property named prop, JavaScript follows the link, then the next link, until it finds the property or reaches null. That linked list is the prototype chain.

flowchart LR
  A["rex (own: name)"] --> B["Dog.prototype (speak)"]
  B --> C["Object.prototype (toString)"]
  C --> D["null"]

Property lookup walks the chain from the object toward null.

Two names confuse many candidates. Dog.prototype is a property on a constructor function: the object that becomes the prototype of instances created with new Dog(). Object.getPrototypeOf(rex) (or the legacy rex.__proto__) is the actual link of an instance. They point to the same object.

JS Walking the chain

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Good talking points: methods live once on the prototype instead of being copied into every instance, which saves memory; in checks the whole chain while Object.hasOwn checks only the object itself; and assigning a property always creates an own property, it never changes the prototype.

Classes are syntax over prototypes

A frequent question: "Are JavaScript classes real classes?" The honest answer: class is cleaner syntax over constructors and prototypes. Under the hood methods still sit on Class.prototype, and typeof SomeClass is "function". A few differences are real, though: class bodies run in strict mode, class declarations are not usable before their definition (they sit in the temporal dead zone, see scope, hoisting and closures), and calling a class without new throws.

JS Classes, inheritance and private fields

Press Run (or Ctrl + Enter) to see the console output here.

No output.

extends does two things: it links Savings.prototype to Account.prototype (for instances), and it links Savings itself to Account (so static members are inherited). #balance is truly private. It is not a naming convention like the older _balance: even s["#balance"] finds nothing, and accessing it from outside is a syntax error.

Common follow-up questions

  • What does new do? It creates an empty object, links its prototype to Constructor.prototype, runs the constructor with this set to that object, and returns it (unless the constructor returns another object).
  • Why put methods on the prototype? One shared copy instead of one per instance. Classes do this automatically for methods, but not for class-field arrow functions.
  • Object.create(null)? An object with no prototype at all, handy as a clean dictionary with no inherited keys like toString.
  • How do you fix a lost this in a callback? Use an arrow function, bind, or call the method through the object (() => user.whoAmI()).

this in every context, void 0, innerHTML and the newest ES features

The four rules above explain how this is chosen for a call. Interviewers also ask for this in less obvious places, about oddities such as void 0, about innerHTML safety, and what is new in recent ECMAScript editions. (Cookies versus Web Storage is already covered in Browser and Networking Questions.)

What is this in each context?

Where the code runs this is
Top level of a classic <script> window (the global object)
Top level of an ES module (type="module") undefined
Plain function call, sloppy mode The global object
Plain function call, strict mode (or inside a module or a class) undefined
Method call obj.m() obj
call, apply, bind The object you pass (sloppy mode wraps primitives)
Constructor with new The new object
Arrow function The this of the enclosing scope (never its own)
DOM event handler written as function () {} event.currentTarget (the element the listener is on)
DOM event handler written as an arrow function The outer this, not the element
Inline attribute onclick="..." The element
Class field arrow function The instance (it is created per instance)
Static method or static block The class itself
setTimeout(function () {...}) The global object in sloppy mode, undefined in strict mode
Getter or setter The object the property is read from

Two rules explain almost every row: this is decided at call time for ordinary functions, and at definition time for arrow functions. When in doubt, look at the left of the dot.

JS this in an arrow, a callback, a class field and a static method

Press Run (or Ctrl + Enter) to see the console output here.

No output.

What does void 0 mean?

void is an operator that evaluates its operand and returns undefined. void 0 is just a short, reliable way to write undefined. In old browsers undefined was a global variable that could be reassigned (undefined = 5), so cautious libraries wrote void 0; today undefined is read-only in the global scope, but a local variable or parameter named undefined is still legal, and void 0 also appears in minified code because it is shorter. The other place you see it is href="javascript:void(0)", an old trick for a link that does nothing, which you should not write today: use a <button>.

JavaScript
console.log(void 0 === undefined);   // true
console.log(void "anything");        // undefined
// Arrow function that must return nothing, so a result is never leaked:
const onClick = () => void doWork();

innerHTML, textContent and XSS

Q: What is the difference between innerHTML and textContent, and why does it matter for security? textContent treats the string as text: <b> shows up literally. innerHTML parses the string as HTML. If that string contains user input, an attacker can inject markup that runs script: this is cross-site scripting (XSS). (A <script> tag inserted through innerHTML does not run, but <img src=x onerror=...> does.)

Safe habits: use textContent or build nodes with createElement; escape user text before putting it into HTML; sanitize rich text with a proven library or the browser's setHTML (Sanitizer API) where available; send a Content Security Policy; and set the attributes of nodes instead of concatenating attribute strings. insertAdjacentHTML and outerHTML have the same risk as innerHTML. Modern frameworks escape by default, and their "dangerously set HTML" escape hatches exist to remind you.

JavaScript
// Read-only: needs a DOM
const comment = '<img src=x onerror="stealCookies()">';
box.innerHTML = comment;          // DANGEROUS: parsed as HTML, the handler runs
box.textContent = comment;        // safe: shown as text

The escaping function itself is plain JavaScript, so you can run it here. It must escape & first, and in attribute values also quotes.

JS Escape user text before putting it into HTML

Press Run (or Ctrl + Enter) to see the console output here.

No output.

What is new in ES2025 and recent proposals?

ECMAScript ships one edition per year. These recent additions are asked about because they replace code people used to write by hand. All of them run in current Chrome, Firefox and Safari and in Node 24; check the JavaScript reference or a compatibility table for the exact versions your users have.

  • Set methods: union, intersection, difference, symmetricDifference, isSubsetOf, isSupersetOf, isDisjointFrom. They return new sets.
  • Iterator helpers: iterators (including generators) get map, filter, take, drop, flatMap, reduce, toArray, some, every, find and forEach, and they are lazy: nothing is computed until you pull values, so an infinite generator is fine with take.
  • Promise.try(fn): runs fn and gives a promise whether fn returns a value, returns a promise, or throws synchronously. It replaces new Promise(r => r(fn())).
  • RegExp.escape(str): escapes special characters so user text can be used safely inside a regular expression.
  • Regular expression (?i:...) modifiers and duplicate named groups, import attributes (import data from "./x.json" with { type: "json" }), and Float16Array.
  • Also worth knowing from recent years: Object.groupBy, Map.groupBy, Array.prototype.toSorted/toReversed/with (non-mutating), structuredClone, Array.prototype.at, Object.hasOwn, top-level await, and Promise.withResolvers.
JS Set methods, lazy iterator helpers, Promise.try and groupBy

Press Run (or Ctrl + Enter) to see the console output here.

No output.

If a feature is missing in an older browser, a polyfill adds it (for example core-js), and a build tool such as Babel can transform syntax; new syntax cannot be polyfilled, but new methods usually can.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does this equal inside a regular function called as fn() in strict mode?

    A plain call has no receiver. In strict mode this is undefined; in sloppy mode it falls back to the global object.
  2. 2. Which method runs the function immediately and takes arguments as an array?

    apply takes an array of arguments and runs now. call takes them one by one. bind returns a new function without running it.
  3. 3. What happens when you assign rex.speak = ... and speak also exists on the prototype?

    Assignment creates or updates an own property. The prototype is only read during lookup, so other instances are unaffected.
  4. 4. Which statement about JavaScript classes is correct?

    Methods live on Class.prototype. Private # fields are not ordinary properties, and calling a class without new throws a TypeError.

Summary

  • this depends on the call: new, explicit call/apply/bind, method call, or plain call. Arrow functions inherit it.
  • Copying a method into a variable loses its object. Fix it with an arrow function or bind.
  • call and apply run now; bind returns a new function.
  • Property lookup walks the prototype chain; assignment creates own properties.
  • class is syntax over prototypes, with strict mode, extends, static and truly private # fields.
  • this is set at call time for ordinary functions and at definition time for arrows; module and strict code give undefined for a plain call.
  • void 0 is undefined; innerHTML parses HTML (XSS risk) while textContent treats text literally, so escape or sanitize user input.
  • ES2025 additions include Set methods, lazy iterator helpers, Promise.try and RegExp.escape.

Next: Promises, async/await and the Event Loop.