개발

Static and non-static(instance) methods

senyalog 2023. 11. 12. 15:54

1. Definition and Access

static instance
Belog to the class itself, not to instances of the class. 

e.g) call them on the class directly
-> Classname.staticMethod()
Belog to instances of the class. Need to create an object of the class to use these methods.

e.g ) const obj = new ClassName();
obj.instanceMethod()

 

2. Use of 'this' keyword

static instance
Cannot use 'this' to refer to an instance of the class, as they do not have access to data stored in specific objects unless passed exlicitly.

Can use 'this' to refer to the instance of the class they belog to, allowing them to access other instance methods and properties of that particular object.

 

3. Purpose

static instance
Used for utility functions that don't require the objct's state(i.e, properties). They can't access instance properties methods directly and are often used for operations that apply to the entire class.(factory methods) Used to operate on the data of specific objects. They can access and modify the state of individual instances.

 

more about factory methods?

- Factory method is a creational design patter that provides an interface for creating objects in a superclass, but allows subclasses to alter th type of objects that will be created.

 

4. Memory allocation

static instance
Since they belong to the class, they are loaded into memory once, at the start of the execution. They are not duplicated across instances.

A new copy of each method is created in meomory for every instance of the class.