Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static method instead of Prototype method Javascript

Tags:

javascript

When instance function are called in a class each instance of object get own copy of function but in prototype method and static method no copy is created , they belong to class, so if they both doesn't create a copy of their function, so why do we have static function if we can simply use prototype method if we don't want to copy??

I am a little bit confuse, if anyone can explain it will be a great help

like image 410
Nikhil Chandna Avatar asked May 28 '26 11:05

Nikhil Chandna


2 Answers

In order to use a prototype/instance method, you need to either have an instance of an object or specifically access the type's .prototype. For methods that don't require an instance, a static method provides simpler syntax. Think of the String.fromCharCode() method as an example. It wouldn't make sense to say:

let str = "dummy string".fromCharCode(127);

The extra string instance there is just a distraction from what you're really trying to do:

let str = String.fromCharCode(127);

This applies good programming practices of reduced coupling (not requiring an instance in order to invoke a method that doesn't need it) and information hiding (by not exposing a method on instances of objects which doesn't pertain to those specific objects).

like image 96
StriplingWarrior Avatar answered May 31 '26 23:05

StriplingWarrior


A static method does not exist on instances. Prototype methods do. So, if you want to call someArr.filter(x => x > 5) that would be an instance method that works on the given array.

An example of astatic method is Array.isArray(someArr). It makes very little sense to make the static method an instance method because you'd need an instance before calling it. That would lead to code like someArr.isArray(someArr) which is illogical - you need an array to check if something is an array. And that can very easily be fail spectacularly if someArr is not in fact an array:

const someArr = { 
  isArray() { return true; },
  filter()  { return "I am not an array"; },
};


console.log(someArr.isArray(someArr));
console.log(someArr.filter(x => x > 5));

Yes, that example is indeed highly illogical in order to highlight why it is weird. Assuming .isArray() was an instance method, you could create a new array in order to use it to call [].isArray(someArr). But that method does not require any instance data. The object created exists only to give you access to the method and is discarded immediately afterwards. That design is still not sensible.

like image 45
VLAZ Avatar answered May 31 '26 22:05

VLAZ