If you've ever written new Person("Alice") and wondered what's actually happening behind the scenes — this post is for you.
what is constructor function?
A constructor function is just a regular function, but by convention we capitalize its name to signal it should be called with new.
function Person(name, age) {
this.name = name;
this.age = age;
}
Inside it, this refers to the new object being built. That's the key idea.
What does new actually do?
When you write:
const alice = new Person("Alice", 30);
JavaScript silently does four things for you:
- Creates a brand-new empty object
// internally: const this = {};
2.Links it to the constructor's prototype
// internally: this.__proto__ = Person.prototype;
This is how alice can call methods like greet() even though they aren't stored on alice itself.
3.Runs the constructor body with this as that new object
this.name = "Alice";
4.Returns the object automatically.You don't need a return statement — new handles it
Putting methods on the prototype
Instead of copying a method into every instance (wasteful!), you add it once to the prototype:
Person.prototype.greet = function() {
console.log("Hi, I'm " + this.name);
};
const alice = new Person("Alice", 30);
const bob = new Person("Bob", 25);
alice.greet(); // "Hi, I'm Alice"
bob.greet(); // "Hi, I'm Bob"
Both alice and bob share the same greet function. Neither instance stores a copy — they just look up the chain.
The prototype chain
When you call alice.greet(), JavaScript searches in this order:
Does alice have greet directly? → No
Does alice.proto (= Person.prototype) have greet? → Yes! Use it.
This chain of lookups is called the prototype chain.
Summary:
- A constructor function is a blueprint for creating objects.
- new creates an empty object, links its prototype, runs the constructor, and returns the result.
- Own data lives on the instance; shared methods live on the prototype.
- When a property isn't found on the instance, JavaScript walks up the prototype chain to find it.
Top comments (0)