Mike
Mike

Reputation: 1738

Javascript objects in their own class file

I am building a site based completely off REST services with a Java backend. I have moderate experience in both Java and PHP, but very little with JavaScript (outside some basic Jquery stuff). My question is do all JavaScript objects have to be defined in a single file, or can they be created in their own class files (like in Java or PHP)? Basically, I want to define a bunch of objects (such as user, product, cart, etc) and then instantiate those objects through REST services on my server, but I am not sure if I have to define all of the objects and the implementation of those objects in one giant file or if I can split them up into several files (like I am used to working with in other OOP languages).

I know you define an object like:

function Car(model, year)
{
    this.model = model;
    this.year = year;
}

Upvotes: 1

Views: 2981

Answers (3)

phnkha
phnkha

Reputation: 7872

You can split classes to separated files and include them when needed. But the order you include your javascript files is very important. For a large scale system you need a framework to manage them. I recommend using Requirejs

Upvotes: 2

Matti Virkkunen
Matti Virkkunen

Reputation: 65126

Yes, you can split code into multiple files, but you'll also have to load all of those files. Multiple <script src="..."></script> elements in a row is theoretically the same as putting all the scripts in one file in the same order. This will cause multiple HTTP requests though, each of which will slow down your page load time, so many people use a tool to automatically combine many files into one.

Upvotes: 2

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382132

There is no constraint in javascript, other than the ones you give yourself.

It's usual to group small related classes in common files, and to isolate them in their dedicated files when they grow big enough.

It's only a matter of readability and maintainability.

As it's important to minimize the number of requests made by the browser for better performances, you should concatenate and minify your javascript files if you create many of them.

Upvotes: 2

Related Questions