Interview question
What is the difference between __proto__ and prototype? __proto__ और prototype में क्या अंतर है?
Answer
| Property | Exists on | Purpose |
|---|---|---|
| prototype | Functions (specifically constructor functions/classes) | The object that will become the __proto__ of instances created with 'new' |
| __proto__ | Every object instance | The actual link to that object's prototype (accessor for the internal [[Prototype]]) |
function Person(name) {
this.name = name;
}
Person.prototype.greet = function() {
return `Hi, I'm ${this.name}`;
};
const john = new Person('John');
// Person.prototype is the blueprint object
console.log(typeof Person.prototype); // 'object'
// john.__proto__ points to Person.prototype
console.log(john.__proto__ === Person.prototype); // true
// This is how john can access greet() even though it's not john's own property
console.log(john.hasOwnProperty('greet')); // false
console.log(john.greet()); // Hi, I'm John - found via __proto__ chain
// Modern way to get/set the prototype (preferred over direct __proto__ access)
console.log(Object.getPrototypeOf(john) === Person.prototype); // true
Object.setPrototypeOf(john, Person.prototype); // equivalent to john.__proto__ = ...
// Functions themselves have BOTH a prototype property AND a __proto__
console.log(typeof Person.prototype); // 'object' - used by 'new'
console.log(Person.__proto__ === Function.prototype); // true - Person is itself an object/function
// Only functions (used as constructors) have a meaningful .prototype property
console.log(john.prototype); // undefined - john is not a function| Property | किस पर है | उद्देश्य |
|---|---|---|
| prototype | Functions (constructor functions/classes) | 'new' से बने instances का __proto__ बनने वाला object |
| __proto__ | हर object instance | उस object के prototype का actual link |
function Person(name) {
this.name = name;
}
Person.prototype.greet = function() {
return `Hi, I'm ${this.name}`;
};
const john = new Person('John');
console.log(typeof Person.prototype); // 'object'
// john.__proto__ Person.prototype की ओर point करता है
console.log(john.__proto__ === Person.prototype); // true
console.log(john.hasOwnProperty('greet')); // false
console.log(john.greet()); // Hi, I'm John
// Modern तरीका
console.log(Object.getPrototypeOf(john) === Person.prototype); // true
Object.setPrototypeOf(john, Person.prototype);
// Functions में दोनों होते हैं
console.log(typeof Person.prototype);
console.log(Person.__proto__ === Function.prototype); // true
// सिर्फ functions के पास meaningful .prototype होता है
console.log(john.prototype); // undefinedWas this answer clear?