Skip to content

Instantly share code, notes, and snippets.

@crwang
Last active August 29, 2015 14:00
Show Gist options
  • Save crwang/11042728 to your computer and use it in GitHub Desktop.
Save crwang/11042728 to your computer and use it in GitHub Desktop.
JS Class example
// Class definition / constructor
var Vehicle = (function() {
/** @const */ var SPEED_LIMIT = 5;
/**
* A vehicle.
*
* @constructor
* @this {Vehicle}
* @param {string} color Vehicle color.
* @param {number} initSpeed Vehicle's initial speed.
*/
var _Vehicle = function(color, initSpeed) {
// Initialization
this._color = color;
// Other member vars
this._speed = 0;
if (initSpeed)
this._speed = initSpeed;
}
_Vehicle.staticMethod = function () { alert('hello world')};
// "Class"-wide methods.
_Vehicle.prototype = {
/**
* Returns the status of the vehicle.
*
* @this {Vehicle}
* @return {string} The status.
*/
getStatus: function () {
var text;
// ok
if (this._speed > SPEED_LIMIT) {
return "Over the speed limit! Color: " + this._color + " Speed: " + this.getSpeed();
}
return "Vroom! Color: " + this._color + " Speed: " + this.getSpeed();
},
/**
* Speeds up the vehicle.
*
* @this {Vehicle}
* @amount {number} The amount to speed it up.
*/
speedUp: function (amount) {
if (amount)
this._speed += amount;
else
this._speed++;
return this._speed;
},
/**
* Slows down the vehicle.
*
* @this {Vehicle}
* @amount {number} The amount to slow it up.
*/
slowDown: function (amount) {
if (amount)
this._speed -= amount;
else
this._speed--;
return this._speed;
},
/**
* Gets the current speed of the vehicle.
*
* @this {Vehicle}
* @return {number} The current speed of the vehicle.
*/
getSpeed: function() { return this._speed; }
};
return _Vehicle;
})();
// Instance methods
//console.log(test.Vehicle);
var v1 = new Vehicle('blue', 10);
var v2 = new Vehicle('red');
v1.speedUp();
v1.speedUp();
v1.speedUp();
v2.slowDown();
v2.slowDown();
v2.slowDown();
console.log(v1.getStatus());
console.log(v2.getStatus());
console.log(v2.getSpeed());
Vehicle.staticMethod();
// console.log(SPEED_LIMIT); // Error, not defined outside of closure
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment