Created
May 15, 2013 15:45
-
-
Save varemenos/5584965 to your computer and use it in GitHub Desktop.
JavaScript - The basics of Object Oriented Programming
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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