Skip to content

Instantly share code, notes, and snippets.

@varemenos
Created May 15, 2013 15:45
Show Gist options
  • Save varemenos/5584965 to your computer and use it in GitHub Desktop.
Save varemenos/5584965 to your computer and use it in GitHub Desktop.
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);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment