简体   繁体   中英

How to keep Javascript Clean

I am just starting out with javascript having worked with C# and OO languages for many years.

I am finding that I am putting my code in files like this,

database.js
sync.js
date.js

And it is feeling very procedural, basically just a bunch of public functions that can be called from anywhere. Can javascript be made to be object oriented, or cleaner than this?

To me it seems like this will become very large and messy quite easily.

Javascript is does not use "classical" object orientation in the way that you are use to, it uses a different object-orientation scheme labeled "Prototypal". I suggest you read up on this to extract the most out of the strengths of the language.

http://javascript.crockford.com/prototypal.html

Sure it can, use a module build like modul8 or browserify

Then rewrite your code like so

// date.js
var dateUtils = {
  ...
};

module.exports = dateUtils;

// database.js

var database = module.exports = {
  ...
};

// sync.js

var sync = module.exports = {
  ...
}

// main.js

var sync = require("./sync.js"),
    database = require("./database.js"),
    date = require("./date.js");

/* main body of code */

Of course if you want OO then use OO. JavaScript has prototypical OO, I have a series about prototypical OO that's worth reading.

And the following gist illustrates a good pattern for OO.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM