JavaScript Prototypes and Constructor Functions Explained
Every JavaScript object has a hidden link to another object, its prototype, and it can use that object’s properties and methods as if they were its own. This is how [1, 2].map works even though you never defined map, and it is what JavaScript classes are built on. In this lesson you will learn how prototypes and the prototype chain work, how to create objects with Object.create and constructor functions, why methods belong on the prototype, and how this knowledge explains classes, instanceof and some confusing errors.
📖 What You’ll Learn: what a prototype is, the prototype chain and property lookup, Object.getPrototypeOf and Object.create, own versus inherited properties, constructor functions and the new keyword, putting methods on Function.prototype, instanceof, built-in prototypes, why you should not modify them, and how classes are syntax over prototypes.
🧬 What Is a Prototype?
Definition: a prototype is an object that another object inherits properties from. Every object has an internal link (written [[Prototype]] in the specification) to its prototype, or to null at the end. When you read a property that the object does not have, JavaScript looks for it on the prototype.
📄 prototype.js
const user = { name: "Asha" };
console.log(user.name); // own property
console.log(user.toString()); // not defined on user... found on its prototype
console.log(Object.getPrototypeOf(user) === Object.prototype);
console.log(Object.hasOwn(user, "toString"), "toString" in user);
⌨️ Terminal
node prototype.js
🖥️ Output
Asha
[object Object]
true
false true
user has only one own property, name. toString comes from Object.prototype, the prototype of every plain object.
⛓️ The Prototype Chain
Definition: a prototype can have its own prototype, forming a prototype chain. Property lookup walks up the chain until it finds the property or reaches null, in which case the result is undefined.
📄 chain.js
const scores = [91, 78];
const p1 = Object.getPrototypeOf(scores); // Array.prototype
const p2 = Object.getPrototypeOf(p1); // Object.prototype
const p3 = Object.getPrototypeOf(p2); // null: end of the chain
console.log(p1 === Array.prototype, p2 === Object.prototype, p3);
console.log(typeof scores.map, typeof scores.hasOwnProperty, scores.fly);
// scores -> Array.prototype (map, push, ...) -> Object.prototype (toString, hasOwnProperty, ...) -> null
⌨️ Terminal
node chain.js
🖥️ Output
true true null
function function undefined
| Value | Its prototype chain |
|---|---|
{} | Object.prototype → null |
[] | Array.prototype → Object.prototype → null |
function () {} | Function.prototype → Object.prototype → null |
"text" (when a method is called) | String.prototype → Object.prototype → null |
Writing a property always creates or changes an own property; it never changes the prototype. An own property with the same name shadows the inherited one:
📄 shadow.js
const base = { greet() { return "hello from base"; } };
const child = Object.create(base);
console.log(child.greet());
child.greet = () => "hello from child"; // own property shadows the inherited one
console.log(child.greet(), "|", base.greet());
⌨️ Terminal
node shadow.js
🖥️ Output
hello from base
hello from child | hello from base
🛠️ Object.create: Choose the Prototype
Object.create(proto) creates a new, empty object whose prototype is proto. It is the most direct way to set up inheritance between plain objects:
📄 object-create.js
const animal = {
describe() {
return `${this.name} says ${this.sound}`;
},
};
const dog = Object.create(animal);
dog.name = "Rex";
dog.sound = "woof";
console.log(dog.describe());
console.log(Object.getPrototypeOf(dog) === animal);
console.log(Object.keys(dog)); // describe is inherited, not an own key
const bare = Object.create(null); // no prototype at all
bare.key = "value";
console.log(typeof bare.toString);
⌨️ Terminal
node object-create.js
🖥️ Output
Rex says woof
true
[ 'name', 'sound' ]
undefined
Object.create(null) creates an object with no prototype, which is a clean dictionary with no inherited keys like toString or constructor.
🏗️ Constructor Functions and new
Before classes (ES2015), objects of the same “type” were created with constructor functions: regular functions called with new. By convention their names start with a capital letter.
📄 constructor.js
function TestCase(name, priority) {
this.name = name;
this.priority = priority;
this.status = "pending";
}
const login = new TestCase("login", "P1");
const search = new TestCase("search", "P2");
console.log(login, search.name);
⌨️ Terminal
node constructor.js
🖥️ Output
TestCase { name: 'login', priority: 'P1', status: 'pending' } search
When you call a function with new, JavaScript:
- Creates a new empty object.
- Sets that object’s prototype to the function’s
prototypeproperty (TestCase.prototype). - Runs the function with
thispointing to the new object. - Returns the new object (unless the function explicitly returns a different object).
⚠️ Watch out: Forgetting new calls the constructor as a plain function: this is undefined in strict mode (TypeError) or the global object in sloppy mode (properties leak onto the global object), and the call returns undefined. Classes prevent this by throwing if you forget new.
📄 forgot-new.js
"use strict";
function TestCase(name) {
this.name = name;
}
try {
const t = TestCase("login"); // forgot new
} catch (e) {
console.log(e.constructor.name + ":", e.message);
}
⌨️ Terminal
node forgot-new.js
🖥️ Output
TypeError: Cannot set properties of undefined (setting 'name')
📎 Methods Belong on the Prototype
If a constructor assigns a method with this.run = function () {...}, every object gets its own copy of the function. Putting the method on Constructor.prototype stores it once, and every object finds it through the prototype chain:
📄 prototype-methods.js
function TestCase(name) {
this.name = name;
this.status = "pending";
}
TestCase.prototype.run = function (passed) {
this.status = passed ? "passed" : "failed";
return this;
};
TestCase.prototype.toString = function () {
return `[${this.status.toUpperCase()}] ${this.name}`;
};
const a = new TestCase("login").run(true);
const b = new TestCase("cart").run(false);
console.log(String(a), "|", String(b));
console.log(a.run === b.run); // one shared function
console.log(Object.hasOwn(a, "run"), Object.getPrototypeOf(a) === TestCase.prototype);
⌨️ Terminal
node prototype-methods.js
🖥️ Output
[PASSED] login | [FAILED] cart
true
false true
| Term | What it is |
|---|---|
Fn.prototype | A property of a constructor function: the object that instances created with new Fn() will inherit from |
Object.getPrototypeOf(obj) | The actual prototype of an object (the modern, standard way to read it) |
obj.__proto__ | Legacy accessor for the same thing; avoid it in new code |
Fn.prototype.constructor | Points back to Fn |
🔎 instanceof and Checking Prototypes
obj instanceof Fn checks whether Fn.prototype appears anywhere in obj‘s prototype chain:
📄 instanceof.js
function Page(url) { this.url = url; }
const home = new Page("/");
console.log(home instanceof Page, home instanceof Object, home instanceof Array);
console.log(Page.prototype.isPrototypeOf(home));
console.log(home.constructor === Page, home.constructor.name);
console.log([] instanceof Array, Array.isArray([]));
⌨️ Terminal
node instanceof.js
🖥️ Output
true true false
true
true Page
true true
💡 Tip: For arrays prefer Array.isArray: instanceof Array can be false for arrays from another frame or realm (for example an iframe, or data passed from page.evaluate in some setups).
⚠️ Built-in Prototypes: Look, Do Not Touch
Because all arrays share Array.prototype, adding a method there makes it appear on every array in the program, including in libraries you did not write:
📄 monkey-patch.js
Array.prototype.last = function () { // monkey patching: do not do this in real code
return this[this.length - 1];
};
console.log([1, 2, 3].last());
const list = ["a", "b"];
for (const key in list) console.log("for...in sees:", key); // the patch leaks into for...in
delete Array.prototype.last;
console.log(typeof [].last, [1, 2, 3].at(-1)); // use the standard at() instead
⌨️ Terminal
node monkey-patch.js
🖥️ Output
3
for...in sees: 0
for...in sees: 1
for...in sees: last
undefined 3
⚠️ Watch out: Modifying built-in prototypes (“monkey patching”) can break other code and future JavaScript versions that add a method with the same name. Write a helper function instead, such as const last = (arr) => arr.at(-1).
🏛️ Classes Are Built on Prototypes
The class syntax (next lesson) is a clearer way to write constructor functions and prototype methods. Under the hood it creates exactly the same structure:
📄 class-prototype.js
class TestCase {
constructor(name) {
this.name = name;
}
run() {
return `running ${this.name}`;
}
}
const t = new TestCase("login");
console.log(typeof TestCase); // classes are functions
console.log(Object.getPrototypeOf(t) === TestCase.prototype); // same prototype link
console.log(Object.hasOwn(TestCase.prototype, "run")); // methods live on the prototype
console.log(Object.keys(t), t.run());
⌨️ Terminal
node class-prototype.js
🖥️ Output
function
true
true
[ 'name' ] running login
🧪 Tester Scenario: Shared Behaviour for Page Objects
A shared base object can provide common helpers to many page objects through the prototype chain. This prototype-based version shows what classes and extends do for you later:
📄 page-prototype.js
const basePage = {
open() {
return `open ${this.baseURL}${this.path}`;
},
title() {
return `${this.name} | SQA Tools`;
},
};
function createPage(name, path) {
const page = Object.create(basePage);
page.name = name;
page.path = path;
page.baseURL = "https://qa.example.com";
return page;
}
const login = createPage("Login", "/login");
const cart = createPage("Cart", "/cart");
login.submit = function (user) { return `${this.name}: submit ${user}`; }; // page-specific method
console.log(login.open(), "|", cart.open());
console.log(cart.title());
console.log(login.submit("asha"), "|", typeof cart.submit);
console.log(Object.getPrototypeOf(login) === Object.getPrototypeOf(cart));
⌨️ Terminal
node page-prototype.js
🖥️ Output
open https://qa.example.com/login | open https://qa.example.com/cart
Cart | SQA Tools
Login: submit asha | undefined
true
📝 Practice Questions with Answers
Try each question on your own first, then open the answer to check your work. Run the code with node practice.js.
Q1. Create const base = { kind: "base" } and const child = Object.create(base). Show that child.kind is “base”, that it is not an own property, and that setting child.kind does not change base.
Show answer
📄 practice1.js
const base = { kind: "base" };
const child = Object.create(base);
console.log(child.kind, Object.hasOwn(child, "kind"));
child.kind = "child";
console.log(child.kind, base.kind, Object.hasOwn(child, "kind"));🖥️ Output
base false
child base trueQ2. Print the full prototype chain of the string object new String("qa") by walking Object.getPrototypeOf until null.
Show answer
📄 practice2.js
let obj = new String("qa");
const chain = [];
while ((obj = Object.getPrototypeOf(obj)) !== null) {
chain.push(obj.constructor.name + ".prototype");
}
console.log(chain.join(" -> ") + " -> null");🖥️ Output
String.prototype -> Object.prototype -> nullQ3. Write a constructor function Product(name, price) with a prototype method withTax(rate) that returns the price including tax. Create two products and show they share the method.
Show answer
📄 practice3.js
function Product(name, price) {
this.name = name;
this.price = price;
}
Product.prototype.withTax = function (rate) {
return +(this.price * (1 + rate)).toFixed(2);
};
const pen = new Product("Pen", 10);
const lamp = new Product("Lamp", 899);
console.log(pen.withTax(0.18), lamp.withTax(0.18), pen.withTax === lamp.withTax);🖥️ Output
11.8 1060.82 trueQ4. Check whether [], {} and new Date() are instances of Object, and whether Object.create(null) is.
Show answer
📄 practice4.js
console.log([] instanceof Object, {} instanceof Object, new Date() instanceof Object);
console.log(Object.create(null) instanceof Object);🖥️ Output
true true true
falseAn object created with Object.create(null) has no prototype chain, so Object.prototype is not in it.
Q5. Without modifying Array.prototype, write a helper sum(arr) and use it on [4, 5, 6].
Show answer
📄 practice5.js
const sum = (arr) => arr.reduce((total, n) => total + n, 0);
console.log(sum([4, 5, 6]), typeof [].sum);🖥️ Output
15 undefinedQ6. Explain what new does by writing a function myNew(Fn, ...args) that creates an object the same way, and test it with a Point(x, y) constructor.
Show answer
📄 practice6.js
function myNew(Fn, ...args) {
const obj = Object.create(Fn.prototype); // 1 + 2: new object linked to the prototype
const result = Fn.apply(obj, args); // 3: run the constructor with this = obj
return result !== null && typeof result === "object" ? result : obj; // 4
}
function Point(x, y) { this.x = x; this.y = y; }
Point.prototype.sum = function () { return this.x + this.y; };
const p = myNew(Point, 2, 3);
console.log(p, p.sum(), p instanceof Point);🖥️ Output
Point { x: 2, y: 3 } 5 true🧠 MCQ Quiz: Prototypes
10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.
- What happens when you read a property an object does not have?Answer: JavaScript looks for it up the prototype chain. If nothing in the chain has it, the result is undefined.
- What is at the end of every prototype chain?Answer: null. Object.prototype’s prototype is null.
- What does
Object.create(proto)do?Answer: Creates an empty object whose prototype is proto. It is the simplest way to set an object’s prototype. - Where should shared methods of a constructor function be defined?Answer: On Constructor.prototype. Prototype methods are stored once and shared.
- What does
obj instanceof Fncheck?Answer: Whether Fn.prototype is in obj’s prototype chain. It works for classes and constructor functions alike. - Which is the modern way to read an object’s prototype?Answer: Object.getPrototypeOf(obj). __proto__ is legacy; obj.prototype usually does not exist on instances.
- What happens if you assign
child.x = 1when x is inherited?Answer: An own property x is created on child. The own property shadows the inherited one. - What is
typeof class A {}?Answer: “function”. Classes are special functions built on prototypes. - Why is adding methods to Array.prototype a bad idea?Answer: It affects every array, including in libraries, and may clash with future features. Write helper functions instead.
- What does
Object.create(null).toStringgive?Answer: undefined. An object with no prototype inherits nothing.
💼 Interview Questions and Answers
Q1. What is prototypal inheritance?
In JavaScript, objects inherit directly from other objects. Each object has a link to a prototype object; when a property is not found on the object, the engine looks it up along this prototype chain. Constructor functions and classes set up these links automatically (instances link to Constructor.prototype), and Object.create sets them explicitly.
Q2. What is the difference between __proto__ and prototype?
prototype is a property of functions (constructors and classes): it is the object that instances created with new will inherit from. __proto__ (better: Object.getPrototypeOf(obj)) is the actual prototype link of any object. For an instance, Object.getPrototypeOf(instance) === Constructor.prototype.
📄 proto-vs-prototype.js
function Car() {}
const c = new Car();
console.log(Object.getPrototypeOf(c) === Car.prototype, c.prototype, typeof Car.prototype);
⌨️ Terminal
node proto-vs-prototype.js
🖥️ Output
true undefined object
Q3. What does the new keyword do?
It creates a new object, links its prototype to the constructor’s prototype property, calls the constructor with this bound to the new object, and returns that object unless the constructor returns another object. Classes require new; calling a class without it throws a TypeError.
Q4. Are JavaScript classes “real” classes like in Java?
No. class is mostly syntax over constructor functions and prototypes: methods are stored on the prototype, and inheritance is a prototype chain. Classes do add real features, such as mandatory new, strict mode, super, and private #fields, but objects still inherit from objects at runtime, and you can inspect or change those links.
❓ Frequently Asked Questions
🤔 Do I need to learn prototypes if I use classes?
You can write classes without thinking about prototypes, but understanding them explains instanceof, method sharing, inheritance and errors such as “x is not a function” on an object you expected to have that method.
🤔 What is the difference between own and inherited properties?
Own properties are stored on the object itself and appear in Object.keys and JSON. Inherited properties come from the prototype chain and are found by property lookup and in.
🤔 Is Object.setPrototypeOf safe to use?
It works, but changing the prototype of an existing object is slow in most engines. Set the prototype when creating the object with Object.create or a class instead.
🤔 Why do primitives like strings have methods?
When you call a method on a primitive, JavaScript temporarily wraps it in an object (String, Number, Boolean) whose prototype provides the method.
🏁 Summary
- Every object has a prototype link; missing properties are looked up along the prototype chain, ending at null.
Object.create(proto)creates an object with a chosen prototype; writing a property always creates an own property.- Constructor functions called with
newcreate objects linked toFn.prototype; shared methods belong there. instanceofchecks the prototype chain; read prototypes withObject.getPrototypeOf.- Classes are syntax over the same prototype mechanism; never modify built-in prototypes.
Next, continue with Lesson 39: Classes.
🎬 Watch JavaScript and automation tutorials on YouTube!
Subscribe to SqaToolsByDY • Practice on sqatools.in