[[Prototype]]
reference to another object.Object.prototype
is the root of all objects.__proto__
is an accessor that points to the prototype of an object, but it's not recommended for direct usage.__proto__
; instead, use Object.getPrototypeOf()
for better compatibility and clarity.const obj = {};
console.log(Object.getPrototypeOf(obj) === Object.prototype); // true
console.log(obj.__proto__ === Object.prototype); // true
When an object is created using a constructor function, it follows a prototype chain structure:
person (instance)
|
| __proto__
v
Person.prototype
|
| __proto__
v
Object.prototype
|
| __proto__
v
null
This means:
person
object inherits from Person.prototype
.Person.prototype
inherits from Object.prototype
.Object.prototype.__proto__
is null
, indicating the end of the prototype chain.There are two primary ways to implement prototypal inheritance in JavaScript: Constructor functions with prototype
and the Object.create()
approach.
Constructor Function + Prototype
prototype
, ensuring they are shared across all instances.function Animal(name: string) {
this.name = name;
}
Animal.prototype.speak = function () {
return `${this.name} makes a noise`;
};
const dog = new Animal("Dog");
console.log(dog.speak()); // Dog makes a noise
Object.create()
Approach