Vehicle Constructor declares an initial variable, vehicle as an object. - Node.js Object

Node.js examples for Object:Constructor

Description

Vehicle Constructor declares an initial variable, vehicle as an object.

Demo Code


/* Vehicle Constructor declares an initial variable, vehicle as an object.
  public properties that can be set:/*from  w ww. j  a  va2  s .com*/
    name, wheels, passengersNumber
  public method:
    makeNoise
  returns vehicle.
*/

function VehicleConstructor(name, wheels, passengerNumber,speed){
    if (!(this instanceof VehicleConstructor)){
        return new VehicleConstructor(name,wheels,passengerNumber, speed);
    }

    // String used to generate vin number
    var chars = "0123456789ABCEDGHIJKLMNOPQRSTUVWXYZ";

    this.distanceTraveled = 0;
    this.speed = speed;
    this.name = name || "unicycle";
    this.wheels = wheels || 1;
    this.passengerNumber = passengerNumber || 0;

    // Invoke createVin to generate random vin number
    this.vin = createVin();

    function createVin(){
        var vin = '';
        for (var i = 0; i < 17; i+=1 ){
            // Use Math.floor and Math.random to generate random index to access character from char string
            vin += chars[Math.floor(Math.random()*35)];
        }
        return vin;
    }
}


VehicleConstructor.prototype.makeNoise = function(noise){
    if (noise){
    this.noise = noise;
    }
    return this;
};

VehicleConstructor.prototype.move = function(){
    this.makeNoise();
    this.updateDistanceTraveled();
    return this;
};

VehicleConstructor.prototype.checkMiles = function(){
    console.log(this.distanceTraveled);
    return this;
};

VehicleConstructor.prototype.updateDistanceTraveled = function(){
    this.distanceTraveled += this.speed;
    console.log(this.distanceTraveled);
    return this;
};

VehicleConstructor.prototype.pickUpPassengers = function (newPassengers) {
    this.passengerNumber += newPassengers;
};

var car = new VehicleConstructor('car', 4, 2, 40);
var bike = new VehicleConstructor('bike',2,1,80);
var sedan = new VehicleConstructor('sedan', 4, 5, 55);
var bus = new VehicleConstructor('bus', 8, 16, 25);


car.makeNoise("beeeep");
car.move();
console.log(car.noise);
console.log(car);

bike.makeNoise("vroom vroom")
console.log(bike);


sedan.makeNoise("honk honk")
console.log(sedan);


bus.pickUpPassengers(20);
console.log(bus);

bus.move();

Related Tutorials