Interview question
What is the difference between instance methods and static methods regarding prototypes? Prototypes के संदर्भ में instance methods और static methods में क्या अंतर है?
Answer
| Type | Defined on | Called on | Accesses instance data? |
|---|---|---|---|
| Instance method | Constructor.prototype | Individual instances | Yes, via 'this' |
| Static method | The constructor/class itself | The class directly, not instances | No direct instance access |
function Circle(radius) {
this.radius = radius;
}
// Instance method - on the prototype, shared by all instances
Circle.prototype.getArea = function() {
return Math.PI * this.radius ** 2; // uses instance's own 'radius'
};
// Static method - directly on the constructor function
Circle.compare = function(circle1, circle2) {
return circle1.getArea() - circle2.getArea();
};
const c1 = new Circle(5);
const c2 = new Circle(3);
console.log(c1.getArea()); // 78.53... - instance method
console.log(Circle.compare(c1, c2)); // static method, called on Circle directly
// console.log(c1.compare); // undefined - static methods NOT accessible on instances
// ES6 class equivalent
class CircleES6 {
constructor(radius) {
this.radius = radius;
}
getArea() { // instance method - added to CircleES6.prototype
return Math.PI * this.radius ** 2;
}
static compare(c1, c2) { // static method - added directly to CircleES6
return c1.getArea() - c2.getArea();
}
static fromDiameter(diameter) { // common static use: factory methods
return new CircleES6(diameter / 2);
}
}
const circle = CircleES6.fromDiameter(10);
console.log(circle.radius); // 5
// Verifying where each method lives
console.log(CircleES6.prototype.hasOwnProperty('getArea')); // true
console.log(CircleES6.hasOwnProperty('compare')); // true| Type | कहाँ defined | कहाँ call होता है | Instance data access? |
|---|---|---|---|
| Instance method | Constructor.prototype | Individual instances | हाँ, 'this' से |
| Static method | खुद constructor/class | Class पर सीधे | नहीं |
function Circle(radius) {
this.radius = radius;
}
// Instance method - prototype पर
Circle.prototype.getArea = function() {
return Math.PI * this.radius ** 2;
};
// Static method - constructor पर सीधे
Circle.compare = function(circle1, circle2) {
return circle1.getArea() - circle2.getArea();
};
const c1 = new Circle(5);
const c2 = new Circle(3);
console.log(c1.getArea()); // instance method
console.log(Circle.compare(c1, c2)); // static method
// ES6 class equivalent
class CircleES6 {
constructor(radius) {
this.radius = radius;
}
getArea() {
return Math.PI * this.radius ** 2;
}
static compare(c1, c2) {
return c1.getArea() - c2.getArea();
}
static fromDiameter(diameter) {
return new CircleES6(diameter / 2);
}
}
const circle = CircleES6.fromDiameter(10);
console.log(circle.radius); // 5Was this answer clear?