Best practices and examples of how to organize object oriented javascript?

I am new to JavaScript and programming in general. I started building my first web application, and I would like to rewrite it using an object-oriented approach. I have read some articles and chapters of books on object-oriented JS on how to mimic namespaces, module template and so on, but it’s hard for me to think about how to organize my code inside objects, I hope you can help me with this or point me in the right direction with some examples or best practices.

I was thinking of organizing it like jQuery with a namespace (possibly an application) and all the functions of my application inside it, for example app.func1, app.func2, however I have other functions that are used inside those that are utilities, and I wanted to so that they have a different name, maybe something like app.util.func ... Also my code creates custom objects inside my application, but I don’t know where is the place to place them and their constructors inside my namespaces.

Any suggestions, ideas, recommendations, templates or examples of how to organize object oriented javascript? Examples of creating a simple library, such as code, would be great.

Thanks in advance!

+4
source share
1 answer

I read some articles and book chapters on object oriented JS on how to mimic namespaces, ...

I would not model the classic OO paradigm in JavaScript. You must adhere to what is natural for JavaScript.

Do not do classic inheritance. Use prototype inheritance or not inherit at all: composition / decoration looks much better than JavaScript inheritance.

You do not need namespaces. They cause unnecessary indirection and lead to an enterprise code failure. Use a nice module template that hides your functions and variables inside closures.

Try a module loader like RequireJS. You can hide your modules in your files and closures, and let RequireJS do the injection magic of dependencies for you.

Organizing JS application files is a very broad topic. You can organize your classes based on separation of concerns using paradigms such as MVC or MVP. As for the organization of the project, there may be an option to create your application on Maven (and in accordance with its agreements).

Since your question was at a very high level, I just wanted to use some ideas and keywords that you might want on Google and read on. Perhaps after some research, testing, and adversity, you may come back and ask about more specific issues.

+7
source

Source: https://habr.com/ru/post/1336081/


All Articles