For example, if I have a class ImageBlock
and then that class has a complex method modifyImage()
...
class ImageBlock {
/* ... */
modifyImage() {
// A 40 line code, complex code
}
/* ... */
}
When I create a new instance of ImageBlock
, will modifyImage()
will be instantiated too? as another function?
I don't want have two instance of complex method, as it was memory waste. I know another alternative for this, but I don't ask for alternative solution to this, sorry.
CodePudding user response:
as another function?
No, it'll be the exact same function.
class ImageBlock {
/* ... */
modifyImage() {
// A 40 line code, complex code
}
/* ... */
}
const i1 = new ImageBlock();
const i2 = new ImageBlock();
console.log(
i1.modifyImage === i2.modifyImage
);
Methods defined inside a class are put onto the prototype object, once, and then each instance has an internal prototype of that prototype object.
That said, even if it was created anew each time (such as with a class field arrow function in order to preserve reference to this
inside - which is reasonably common) -
as it was memory waste.
A 40 line code
it would be absolutely nothing to worry about in 99.9% of situations. Computers from the past decade can run many thousands of lines in the blink of an eye, and simply creating a function without calling it is much easier than that.