varemenos
5/15/2013 - 3:45 PM

JavaScript - The basics of Object Oriented Programming

JavaScript - The basics of Object Oriented Programming

// Class creation
function Vehicle(p) {
  this.brand = p.brand || "";
	this.model = p.model || "";
	this.wheels = p.wheels || 0;
}

// Main class' methods
Vehicle.prototype.getBrand = function () {
	return this.brand;
};
Vehicle.prototype.getModel = function () {
	return this.model;
};
Vehicle.prototype.getWheels = function () {
	return this.wheels;
};


// object creation
var myVehicle = new Vehicle({
	brand: "Mazda",
	model: "RX8",
	wheels: 4
});

// usage
console.log(myVehicle);
// Main class
function Vehicle(p) {
  this.brand = p.brand || "";
  this.model = p.model || "";
	this.wheels = p.wheels || 0;
}

// Main class' methods
Vehicle.prototype.getBrand = function () {
	return this.brand;
};
Vehicle.prototype.getModel = function () {
	return this.model;
};
Vehicle.prototype.getWheels = function () {
	return this.wheels;
};

// child class
function Car() {
	// inheritance initiation
	Vehicle.apply(this, arguments);
	// property overriding
	this.wheels = 4;
}

// prototype linking
if(Object.create){
	Car.prototype = Object.create(Vehicle.prototype);
}else{
	var temp = function () {};
	temp.prototype = Vehicle.prototype;
	Car.prototype = temp.prototype;
}

// method overriding
Car.prototype.getWheels = function () {
	return 4;
};


// object creation
var myCar = new Car({
	brand: "Mazda",
	model: "RX8"
});

// usage
console.log(myCar);