简体   繁体   中英

Module export multiple classes

This is /cars/ford.js

                   Ford = Car.extend({
                    classId: 'Ford',

                    init: function (driver) {
                        this._driver = driver;
                        Car.prototype.init.call(this);


                    tick: function (ctx) {
                        Car.prototype.tick.call(this, ctx);
                    },

                    destroy: function () {
                        if (this._driver !== undefined) {
                            this._driver._license.pull(this);
                        }
                        Car.prototype.destroy.call(this);
                    }
                });

if (typeof(module) !== 'undefined' && typeof(module.exports) !== 'undefined') {
                module.exports = Ford;
            }

This is /cars/knightrider.js:

                   KITT = Car.extend({
                    classId: 'KITT',

                    init: function () {
                    Car.prototype.init.call(this);
                    var self = this;
                    },


newDirection: function () {
    var self = this;

    this._move.direction()
        .duration(Math.random())
        .properties({
            x: Math.random(),
            y: Math.random(),
        })
        .voice('robotic')
        .afterDirection(function () {
            self.newDirection();
        })
        .start();


}
                });

if (typeof(module) !== 'undefined' && typeof(module.exports) !== 'undefined') {
                module.exports = KITT;
            }

I want to have all cars inside the same file to preserve my self sanity. How can I wrap them without altering my classes? Feel free to recommend any 'proper packaging' for Javascript functions book or tutorial, because I really dislike to open files. When I'm editing a car, I might want to edit other one.

Wish I could do:

        module.exports.Allmycars = KITT, Ford;

And then call them with:

        Allmycars.Ford

A solution could be :

//cars/index.js

module.exports = {
  KITT:require("./knightrider"),
  Ford:require("./ford")
}

//So u could use :

var allMyCars = require("./cars");
var ford = new allMyCars.Ford();

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